﻿using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Anke.SHManage.MSSQLDAL
{

    /// <summary>
    /// 流水数据访问
    /// </summary>
    public class LSDAL
    {

        public static readonly SqlConnectionStringBuilder DispatchBuilder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);//取调度库的链接字符串
        public static readonly string DispatchDatabase = DispatchBuilder.InitialCatalog;

        #region 重大突发性灾害事故流水表
        /// <summary>
        /// 重大突发性灾害事故流水表 2016-11-04 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_ZDTFXZHSG(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
//            sb.Append(@"            
//                select distinct  AlarmEventCode = tae.事件编码,FirstAcceptMoment = 首次受理时刻,AccidentName = tac.现场地址+'('+isnull(tzaccit.名称,'')+')'
//                ,CriticalNumber = sum(重伤人数),CommonNumber = sum(轻伤人数),DeathNumber = sum(死亡人数)
//                ,HospitalNumber = sum(人数)
//                ,RescueCarNumber =count(distinct(tt.任务编码))
//                ,RescuePersonNumber=(select count(人员编码) from TTaskPersonLink where substring(任务编码,1,16)=tae.事件编码)              
//                from  dbo.TAlarmEvent tae 
//                left join TAcceptEvent tac on tac.事件编码=tae.事件编码
//                left join TTask tt on tt.事件编码=tae.事件编码
//                left join TAccidentReport tar on tar.事故编码=tae.事件编码
//                left join TZAccidentType tzaccit on tzaccit.编码=tae.事故类型编码
//                left join TAcdReportDirection tard on tard.事故编码=tae.事件编码               
//                where 事故类型编码!=-1 and 首次受理时刻>='" + beginTime + "' and 首次受理时刻<='" + endTime + @"'
//                and tt.任务编码>'" + taskCodeB + "' and tt.任务编码<='" + taskCodeE + @"'
//                group by tae.事件编码,首次受理时刻,tac.现场地址,tzaccit.名称
//                order by 首次受理时刻 desc");

            //add2021-05-27 plq 适配V8
            sb.Append(@"            
                 select distinct AlarmEventCode=tae.事件编码,FirstAcceptMoment=tae.首次受理时刻,AccidentName=tac.现场地址+'('+isnull(tzaccit.名称,'')+')',
                 CriticalNumber=isnull(sum(tard.重度伤),0),CommonNumber = isnull(sum(tard.轻度伤) +sum(tard.中度伤),0),DeathNumber = isnull(sum(tard.死亡不送)+sum(tard.死亡送院),0),
                 HospitalNumber = isnull(sum(tard.送院人数),0)
                ,RescuePersonNumber=(select count(人员编码) from TTaskPersonLink where substring(任务编码,1,16) in (select 事件编码 from TAlarmEvent where 所属事故编码=tae.事件编码))
                ,RescueCarNumber=(select count(*) from TTask tt where tt.事件编码 in (select 事件编码 from TAlarmEvent where 所属事故编码=tae.事件编码))
                from TAlarmEvent tae
                left join TAcceptEvent tac on tae.事件编码 = tac.事件编码  and tac.受理序号 = tae.受理次数 
                left join TTask tt on tt.事件编码=tae.事件编码 and tae.受理次数 = tt.受理序号
                left join TAcdReportDirection tard on tard.事故编码 in (select 事件编码 from TAlarmEvent where 所属事故编码=tae.事件编码)
                left join TZAccidentType tzaccit on tzaccit.编码=tae.事故类型编码    
                where tae.事故类型编码<>-1 and tae.事件编码 = tae.所属事故编码
                and 首次受理时刻>='" + beginTime + "' and 首次受理时刻<='" + endTime + @"' ");
            sb.Append(@" and tt.任务编码>'" + taskCodeB + "' and tt.任务编码<='" + taskCodeE + @"' "); 
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch  
            sb.Append(@" group by tae.事件编码,tae.事件名称,tae.首次受理时刻,tac.现场地址,tzaccit.名称
                order by 首次受理时刻 desc");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 调度日志流水表
        /// <summary>
        /// 调度日志流水表 2016-11-04 周志猛 ‘TReliefLog’表不存在
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_DDRZ(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
//            sb.Append(@"
//                     if datediff(day,@BeginTime,@EndTime)=0
//                     select 
//                     DeskCode='无',
//                     Date=建立时间,
//                     LastUpdateDate=最后一次修改时间,
//                     Content=内容,
//                     Person=建立者,
//                     LastUpdatePerson=最后修改者
//                     from TNoteBook tnb
//                     --left join TDesk td on td.台号=trl.台号
//                     where 建立时间=convert(char(10),@BeginTime,112)
//                     else
//                     select 
//                     DeskCode='无',
//                     Date=建立时间,
//                     LastUpdateDate=最后一次修改时间,
//                     Content=内容,
//                     Person=建立者,
//                     LastUpdatePerson=最后修改者
//                     from TNoteBook tnb
//                     --left join TDesk td on td.台号=trl.台号
//                     where 建立时间>=convert(char(10),@BeginTime,112) and 建立时间<=convert(char(10),@EndTime,112)
//                        ");
            sb.Append(@"
                     if datediff(day,@BeginTime,@EndTime)=0
                      select 
                     DeskCode=台号,
                     Date=创建时间,
                     LastUpdateDate=修改时间,
                     Content=内容,
                     Person=tp2.姓名,
                     LastUpdatePerson=tp1.姓名
                     from TShiftLog tsl
					 left join TPerson tp1 on tsl.人员编码 = tp1.编码 
					 left join TPerson tp2 on tsl.创建人员编码 = tp2.编码
                     --left join TDesk td on td.台号=trl.台号
                     where 创建时间=convert(char(10),@BeginTime,112)
                     else
                     select 
                     DeskCode=台号,
                     Date=创建时间,
                     LastUpdateDate=修改时间,
                     Content=内容,
                     Person=tp2.姓名,
                     LastUpdatePerson=tp1.姓名
                     from TShiftLog tsl
					 left join TPerson tp1 on tsl.人员编码 = tp1.编码 
					 left join TPerson tp2 on tsl.创建人员编码 = tp2.编码
                     --left join TDesk td on td.台号=trl.台号
                     where 创建时间>=convert(char(10),@BeginTime,112) and 创建时间<=convert(char(10),@EndTime,112)
                        ");
            WhereClauseUtility.AddStringEqual(" tsl.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch

            SqlParameter[] prams = new SqlParameter[] { 
                new SqlParameter("@BeginTime",SqlDbType.DateTime)
               ,new SqlParameter("@EndTime",SqlDbType.DateTime)
            };
            prams[0].Value = beginTime;
            prams[1].Value = endTime;

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), prams);
            return ds.Tables[0];
        }
        #endregion

        #region  发送通知流水表
        /// <summary>
        /// 发送通知流水表
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_FSTZ(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select Operator=tp.姓名,SendTime=发送时刻,Content=内容,SendType=tznt.名称  
                      from TNotice tn
                      left join TPerson tp on tp.编码=tn.操作员编码
                      left join TZNoticeType tznt on tznt.编码=tn.类型编码
                      left join TStation ts on tp.分站编码 = ts.编码
                      where 发送时刻>='" + beginTime + "' and 发送时刻<='" + endTime + @"' and tp.是否有效=1 ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 日常急救到达率分段（时间段）表 2016-11-10 周志猛
        public DataTable Get_LS_RCJJDDLFDSJD(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch

            sb.Append(@"
                --set ansi_warnings off
                set nocount on 
                select 
                --Center=tc.名称,
                AlarmEventType=alet.名称,
                TotalTimes=count(*),
                TimesIn10Minute=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=600 then 1 else 0 end)
                ,TimesBetween10And12Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>600 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=720 then 1 else 0 end)
                ,TimesBetween12And15Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>720 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=900 then 1 else 0 end)
                ,TimesBetween15And20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>900 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=1200 then 1 else 0 end)
                ,TimesOver20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>1200 then 1 else 0 end)               
                from dbo.TTask tt
                inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                left join dbo.TZAlarmEventType alet on alet.编码=ale.事件类型编码
                left join TStation ts on tt.分站编码=ts.编码
                --left join TCenter tc on ts.中心编码=tc.编码
                where 首次受理时刻>='" + beginTime + "' and 首次受理时刻<='" + endTime + @"'
                and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                and tt.任务编码>'" + taskCodeB + "' and tt.任务编码<='" + taskCodeE + @"'
                and 事件类型编码 in (@救治,@回家,@转院) ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                --and ts.中心编码<>1
                group by  
                --tc.名称,
                alet.名称
                order by 
                --tc.名称,
                alet.名称
                set nocount off
                --set ansi_warnings on  
                ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        public DataTable Get_LS_RCJJDDLFDSJDSum(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch

            sb.Append(@"
                select 
                SumAlarmEventType=alet.名称,
                SumTotalTimes=count(*),
                SumTimesIn10Minute=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=600 then 1 else 0 end)
                ,SumTimesBetween10And12Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>600 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=720 then 1 else 0 end)
                ,SumTimesBetween12And15Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>720 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=900 then 1 else 0 end)
                ,SumTimesBetween15And20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>900 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=1200 then 1 else 0 end)
                ,SumTimesOver20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>1200 then 1 else 0 end)
                from dbo.TTask tt
                inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                left join dbo.TZAlarmEventType alet on alet.编码=ale.事件类型编码
                left join TStation ts on tt.分站编码=ts.编码
                where 首次受理时刻>='" + beginTime + "' and 首次受理时刻<='" + endTime + @"'
                and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                and 事件类型编码 in (@救治,@回家,@转院)  ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                --and ts.中心编码<>1
                group by alet.名称
                order by alet.名称
                ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 手机定位成功率统计表
        /// <summary>
        /// 手机定位成功率统计表 2016-11-04 周志猛 ‘TTelLocation’表不存在
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_SJDWCGL(DateTime beginTime, DateTime endTime)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                select ServiceProvider=运营商类型,TotalAlarm=count(电话号码)
                into #temp1
                from dbo.TTelLocation
                where 请求时刻>='" + beginTime + "' and 请求时刻<='" + endTime + @"' 
                and  运营商类型!='未知'
                group by 运营商类型

                select ServiceProvider=运营商类型,SucceedLocation=count(电话号码) 
                into #temp2
                from dbo.TTelLocation
                where 请求时刻>='" + beginTime + "' and 请求时刻<='" + endTime + @"' 
                and  运营商类型!='未知' and 是否定位=1
                group by 运营商类型
                select t1.ServiceProvider,TotalAlarm,SucceedLocation
                from #temp1 t1 left join #temp2 t2 on t1.ServiceProvider=t2.ServiceProvider
                drop table #temp1
                drop table #temp2");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 危重病人病情预报登记表
        /// <summary>
        /// 危重病人病情预报登记表 2016-11-04 周志猛 ‘TGreenDate’表不存在
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_WZBRBQYBDJ(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select 
                    Date=convert(varchar(10),时间,120),
                    Time=convert(varchar(5),时间,114),
                    Name=患者姓名
                    ,Assessment=拟诊
                    ,ToHospital=送往医院
                    ,ReportName=预报人
                    ,RegisterName=登录人
                    ,Remark=tgd.备注
                    ,CarNumber=tam.实际标识

                    from TGreenDate tgd
                    left join TTask tt on tt.任务编码=tgd.任务编码
                    left join TAlarmEvent tae on tt.事件编码 = tae.事件编码
                    left join TAmbulance tam on tam.车辆编码=tt.车辆编码
                    where 时间>='" + beginTime + "' and 时间<='" + endTime + @"' ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                    order by 时间");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 医院搁置担架统计表
        /// <summary>
        /// 医院搁置担架统计表 2016-11-04 周志猛 ‘TLitterLog’表不存在
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_YYGZDJ(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
//            StringBuilder sb = new StringBuilder();
//            sb.Append(@"
//                                select Hosptial=送往医院,Times=count(*)
//                                from TLitterLog tll
//                                left join dbo.TZLitterReasonType tzlrt on tzlrt.编码=tll.原因编码
//                                where 时间>='" + beginTime + "' and 时间<='" + endTime + @"'
//                                group by 送往医院
//                                order by 送往医院");

            //add2021-05-28 plq
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select Hosptial=医院名称,Times=count(*)
                    from TPauseRecord tpr
                    left join dbo.TZPauseReason  tzpr on tzpr.编码=tpr.原因编码
                    where 暂停时刻>='" + beginTime + "' and 暂停时刻<='" + endTime + @"' ");
            WhereClauseUtility.AddStringEqual("tpr.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@" group by 医院名称
                    order by 医院名称 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 医院搁置救护车担架影响出车统计表
        /// <summary>
        /// 医院搁置救护车担架影响出车统计表 2016-11-04 周志猛 ‘TLitterLog’表不存在
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_YYGZJHCDJYXCC(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            //StringBuilder sb = new StringBuilder();
//            sb.Append(@"
//                    select 
//                    Date=convert(varchar(10),时间,120)
//                    ,Time=convert(varchar(5),时间,114)
//                    ,ToHosptial=送往医院
//                    ,Reason=tzlrt.名称
//                    ,StayTime=搁置时间
//                    ,Name=姓名
//                    from TLitterLog tll
//                    left join dbo.TZLitterReasonType tzlrt on tzlrt.编码=tll.原因编码
//                    where 时间>='" + beginTime + "' and 时间<='" + endTime + @"'");

            //add2021-05-28 plq
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select 
                    Date=convert(varchar(10),暂停时刻,120)
                    ,Time=convert(varchar(5),暂停时刻,114)
                    ,ToHosptial=医院名称
                    ,Reason=tzpr.名称
                    ,StayTime=搁置时间
                    ,Name=上报人
                   from TPauseRecord tpr
                    left join dbo.TZPauseReason  tzpr on tzpr.编码=tpr.原因编码  ");
            WhereClauseUtility.AddStringEqual("tpr.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                    where 暂停时刻>='" + beginTime + "' and 暂停时刻<='" + endTime + @"'");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 调度员工作状态流水表
        /// <summary>
        /// 调度员工作状态流水表 2016-11-04 周志猛
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="workState"></param>
        /// <param name="time"></param>
        /// <param name="name"></param>
        /// <param name="personCode"></param>
        /// <returns></returns>
        public DataTable Get_LS_DDYGZZT(DateTime beginTime, DateTime endTime, string workState, string time, string name, string personCode, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                 --set ansi_warnings off
                  select 
                   人员姓名
                  ,开始时刻
                  ,开始类型
                  ,结束时刻
                  ,结束类型
                  ,Time=datediff(second,开始时刻,结束时刻)  
                  ,台号
				  ,开始类型编码=case when tos.开始类型='登录' then 0 when tos.开始类型='电话受理' then 1 when tos.开始类型='手工制表' then 2 
				   when tos.开始类型='就绪' then 3  when tos.开始类型='待警' then 4 else 5 end 
				   into #temp
				   from dbo.TOperatorSignNew tos
				   left join  dbo.TPerson TP ON (tos.人员编码=TP.编码)
				   where 开始时刻>='" + beginTime + "' and 开始时刻<='" + endTime + @"'
                   and (datediff(second,开始时刻,结束时刻)>'" + time + "'*60 or '" + time + @"'='')  and TP.是否有效=1 ");
            WhereClauseUtility.AddStringEqual("tos.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                 select 
                   Name=人员姓名
                  ,StartTime=开始时刻
                  ,StartType=开始类型
                  ,EndTime=结束时刻
                  ,EndType=结束类型
                  ,Time=datediff(second,开始时刻,结束时刻)  
                  ,DeskCode=台号
                  ,StartTypeCode=开始类型编码
                 from  #temp  where 1=1 ");
            WhereClauseUtility.AddStringEqual("人员姓名", name, sb);
            WhereClauseUtility.AddStringLike("tp.工号", personCode, sb);
            WhereClauseUtility.AddInSelectQuery("开始类型编码", workState, sb);

            sb.Append(" order by 人员姓名,开始时刻");
            sb.Append(" drop table #temp ");
            //sb.Append(" set ansi_warnings on ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        public object Get_LS_DDYGZZT_RYXM(string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select tp.编码,tp.姓名
                    from TPerson tp 
                    left join TStation ts on tp.分站编码 = ts.编码 
                    left join TRole tr on tr.编码 = tp.类型编码 
                    where tp.类型编码 = 2 and tp.是否有效 = 1");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["姓名"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 分站人员上下班流水表 2016-11-09 周志猛
        public DataTable Get_LS_FZRYSXB(DateTime beginTime, DateTime endTime,string station, string role, string carNumber, string workCode, string name,
            E_StatisticsPermisson em, string selfName, string selfWorkCode, string selfCenterID, string selfStationID, string eventDispatchCenterID)//去掉了“ string center”
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     SET NOCOUNT ON
                     select  
                             --Center=tc.名称, 
                            Sation=ts.名称 
                            ,Name=tp.姓名
                            ,PersonCode=t.人员编码
                            ,WorkNumber=tp.工号
                            ,CarCode=t.车辆编码
                            ,Role=tr.名称
                            ,CarNumber=ta.实际标识
                            ,OnDutyOperateMoment=t.操作时刻
                            ,OnDutyType=上班方式
                            ,OffDutyOperateMoment=t1.操作时刻
                            ,OffDutyType=下班方式
                     from (select 人员编码,
                                  操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 上班方式
		                    from TAmbulancePersonSign taps
                            left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码 
                              left join TPerson tpa on taps.人员编码=tpa.编码
                              left join TStation ts on tpa.分站编码 = ts.编码
		                    where 操作时刻 >= '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 1 ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
		                    )t
                    left join (select 人员编码,
		                              操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 下班方式
		                      from TAmbulancePersonSign taps
                              left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                              left join TPerson tpa on taps.人员编码=tpa.编码
                              left join TStation ts on tpa.分站编码 = ts.编码
		                       where 操作时刻 >=  '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 0 ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
		                       )t1 on t.操作时刻 = t1.上次操作时刻 and t.人员编码=t1.人员编码 and t.人员类型编码=t1.人员类型编码
                    left join TPerson tp on t.人员编码=tp.编码
                    left join TAmbulance tam on t.车辆编码=tam.车辆编码
                    --left join dbo.TCenter tc on tam.中心编码=tc.编码
                    left join dbo.TStation ts on tam.分站编码 = ts.编码
                    left join TRole tr on t.人员类型编码=tr.编码
                    left join TAmbulance ta on t.车辆编码=ta.车辆编码
                    where 1=1
                    ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            if (em == E_StatisticsPermisson.None)
                return null;
            else if (em == E_StatisticsPermisson.ALL)
            {

                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                //WhereClauseUtility.AddInSelectQuery("tc.编码", center, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                //sb.Append("order by tc.顺序号,t.车辆编码,t.操作时刻");
                sb.Append(@" union 
                             select  
                             --Center=tc.名称, 
                            Sation=ts.名称 
                            ,Name=tp.姓名
                            ,PersonCode=t1.人员编码
                            ,WorkNumber=tp.工号
                            ,CarCode=t1.车辆编码
                            ,Role=tr.名称
                            ,CarNumber=ta.实际标识
                            ,OnDutyOperateMoment=t.操作时刻
                            ,OnDutyType=上班方式
                            ,OffDutyOperateMoment=t1.操作时刻
                            ,OffDutyType=下班方式
                         from  
					    (select 人员编码,
		                              操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 下班方式
		                      from TAmbulancePersonSign taps
                              left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码 
                              left join TPerson tpb on taps.人员编码=tpb.编码
                              left join TStation ts on tpb.分站编码 = ts.编码
		                       where 操作时刻 >=  '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 0 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                       )t1 
				        left join  (select 人员编码,
                                  操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 上班方式
		                    from TAmbulancePersonSign taps
                            left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码 
                              left join TPerson tpb on taps.人员编码=tpb.编码
                              left join TStation ts on tpb.分站编码 = ts.编码
		                    where 操作时刻 >= '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 1 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                    )t on t.操作时刻 = t1.上次操作时刻 and t.人员编码=t1.人员编码 and t.人员类型编码=t1.人员类型编码
                    
                    left join TPerson tp on t1.人员编码=tp.编码
                    left join TAmbulance tam on t1.车辆编码=tam.车辆编码
                    --left join dbo.TCenter tc on tam.中心编码=tc.编码
                    left join dbo.TStation ts on tam.分站编码 = ts.编码
                    left join TRole tr on t1.人员类型编码=tr.编码
                    left join TAmbulance ta on t1.车辆编码=ta.车辆编码
					where 1=1
				");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                //WhereClauseUtility.AddInSelectQuery("tc.编码", center, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.CENTER)
            {

                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                //WhereClauseUtility.AddStringEqual("tc.编码", selfCenterID, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                //sb.Append("order by tc.顺序号,t.车辆编码,t.操作时刻");
                sb.Append(@" union 
                             select  
                             --Center=tc.名称, 
                            Sation=ts.名称 
                            ,Name=tp.姓名
                            ,PersonCode=t1.人员编码
                            ,WorkNumber=tp.工号
                            ,CarCode=t1.车辆编码
                            ,Role=tr.名称
                            ,CarNumber=ta.实际标识
                            ,OnDutyOperateMoment=t.操作时刻
                            ,OnDutyType=上班方式
                            ,OffDutyOperateMoment=t1.操作时刻
                            ,OffDutyType=下班方式
                         from  
					    (select 人员编码,
		                              操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 下班方式
		                      from TAmbulancePersonSign taps
                              left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                                left join TPerson tpc on taps.人员编码=tpc.编码
                              left join TStation ts on tpc.分站编码 = ts.编码
		                       where 操作时刻 >=  '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 0 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                       )t1 
				        left join  (select 人员编码,
                                  操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 上班方式
		                    from TAmbulancePersonSign taps
                            left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                            left join TPerson tp4 on taps.操作人编码=tp4.编码
                            left join TPerson tpd on taps.人员编码=tpd.编码
                            left join TStation ts on tpd.分站编码 = ts.编码
		                    where 操作时刻 >= '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 1 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                    )t on t.操作时刻 = t1.上次操作时刻 and t.人员编码=t1.人员编码 and t.人员类型编码=t1.人员类型编码
                    
                    left join TPerson tp on t1.人员编码=tp.编码
                    left join TAmbulance tam on t1.车辆编码=tam.车辆编码
                    --left join dbo.TCenter tc on tam.中心编码=tc.编码
                    left join dbo.TStation ts on tam.分站编码 = ts.编码
                    left join TRole tr on t1.人员类型编码=tr.编码
                    left join TAmbulance ta on t1.车辆编码=ta.车辆编码
					where 1=1
				");
                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                //WhereClauseUtility.AddStringEqual("tc.编码", selfCenterID, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.STATION)
            {
                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                WhereClauseUtility.AddStringEqual("ts.编码", selfStationID, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                //sb.Append("order by tc.顺序号,t.车辆编码,t.操作时刻");
                sb.Append(@" union 
                             select  
                             --Center=tc.名称, 
                            Sation=ts.名称 
                            ,Name=tp.姓名
                            ,PersonCode=t1.人员编码
                            ,WorkNumber=tp.工号
                            ,CarCode=t1.车辆编码
                            ,Role=tr.名称
                            ,CarNumber=ta.实际标识
                            ,OnDutyOperateMoment=t.操作时刻
                            ,OnDutyType=上班方式
                            ,OffDutyOperateMoment=t1.操作时刻
                            ,OffDutyType=下班方式
                         from  
					    (select 人员编码,
		                              操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 下班方式
		                      from TAmbulancePersonSign taps
                              left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                              left join TPerson tpc on taps.人员编码=tpc.编码
                              left join TStation ts on tpc.分站编码 = ts.编码
		                       where 操作时刻 >=  '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 0  ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                       )t1 
				        left join  (select 人员编码,
                                  操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 上班方式
		                    from TAmbulancePersonSign taps
                            left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                            left join TPerson tpd on taps.人员编码=tpd.编码
                            left join TStation ts on tpd.分站编码 = ts.编码
		                    where 操作时刻 >= '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 1 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                    )t on t.操作时刻 = t1.上次操作时刻 and t.人员编码=t1.人员编码 and t.人员类型编码=t1.人员类型编码
                    
                    left join TPerson tp on t1.人员编码=tp.编码
                    left join TAmbulance tam on t1.车辆编码=tam.车辆编码
                    --left join dbo.TCenter tc on tam.中心编码=tc.编码
                    left join dbo.TStation ts on tam.分站编码 = ts.编码
                    left join TRole tr on t1.人员类型编码=tr.编码
                    left join TAmbulance ta on t1.车辆编码=ta.车辆编码
					where 1=1
				");
                WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
                WhereClauseUtility.AddStringEqual("ts.编码", selfStationID, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.SELF)
            {
                WhereClauseUtility.AddStringLike("tp.姓名", selfName, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringEqual("tp.工号", selfWorkCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                //sb.Append("order by tc.顺序号,t.车辆编码,t.操作时刻");
                sb.Append(@" union 
                             select  
                             --Center=tc.名称, 
                            Sation=ts.名称 
                            ,Name=tp.姓名
                            ,PersonCode=t1.人员编码
                            ,WorkNumber=tp.工号
                            ,CarCode=t1.车辆编码
                            ,Role=tr.名称
                            ,CarNumber=ta.实际标识
                            ,OnDutyOperateMoment=t.操作时刻
                            ,OnDutyType=上班方式
                            ,OffDutyOperateMoment=t1.操作时刻
                            ,OffDutyType=下班方式
                         from  
					    (select 人员编码,
		                              操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 下班方式
		                      from TAmbulancePersonSign taps
                              left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                              left join TPerson tpc on taps.人员编码=tpc.编码
                              left join TStation ts on tpc.分站编码 = ts.编码
		                       where 操作时刻 >=  '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 0 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                       )t1 
				        left join  (select 人员编码,
                                  操作时刻,人员类型编码,车辆编码,操作人编码,是否上班操作,操作来源编码,上次操作时刻
                                  ,tzoo.名称 as 上班方式
		                    from TAmbulancePersonSign taps
                            left join TZOperationOrigin tzoo on taps.操作来源编码=tzoo.编码
                            left join TPerson tpd on taps.人员编码=tpd.编码
                            left join TStation ts on tpd.分站编码 = ts.编码
		                    where 操作时刻 >= '" + beginTime + "' and 操作时刻 <= '" + endTime + @"' and 是否上班操作 = 1 ");
                WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"
		                    )t on t.操作时刻 = t1.上次操作时刻 and t.人员编码=t1.人员编码 and t.人员类型编码=t1.人员类型编码
                    
                    left join TPerson tp on t1.人员编码=tp.编码
                    left join TAmbulance tam on t1.车辆编码=tam.车辆编码
                    --left join dbo.TCenter tc on tam.中心编码=tc.编码
                    left join dbo.TStation ts on tam.分站编码 = ts.编码
                    left join TRole tr on t1.人员类型编码=tr.编码
                    left join TAmbulance ta on t1.车辆编码=ta.车辆编码
					where 1=1
				");
                WhereClauseUtility.AddStringLike("tp.姓名", selfName, sb);
                WhereClauseUtility.AddInSelectQuery("tr.编码", role, sb);
                WhereClauseUtility.AddStringEqual("tp.工号", selfWorkCode, sb);
                WhereClauseUtility.AddStringLike("ta.实际标识", carNumber, sb);
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 下拉框取分中心可多选，连动分站
        //取分中心
        public object GetCenter(string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select 编码,名称 
                      from TCenter where 是否有效 =1 ");
            WhereClauseUtility.AddStringEqual("编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        //根据中心编码取分站 （中心，分站联动，统计流水用）
        //public string ListToString(List<int> list)
        //{
        //    string result = "";
        //    foreach (int i in list)
        //    {
        //        result = result + i.ToString() + ",";
        //    }
        //    return result.TrimEnd(',');
        //}
        //根据中心编码取分站 （中心，分站联动，统计流水用）
        public object GetStation(string centerID, string eventDispatchCenterID)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     select 编码,名称
                     from TStation  ");
            sb.Append("where 是否有效 = 1");
            WhereClauseUtility.AddInSelectQuery("中心编码", centerID, sb);
            WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            //where 中心编码 in (" + centerID + ") and  是否有效 =1 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;
        }

        //根据分站编码取车 （分站，车联动，统计流水用）
        public object GetAmbulanceName(string stationID, string eventDispatchCenterID)
        {

            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                select 编码=车辆编码,名称=实际标识
                from TAmbulance  
                where 是否有效 = 1 ");
            WhereClauseUtility.AddInSelectQuery("分站编码", stationID, sb);
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@" 
                order by 实际标识");
            //where 中心编码 in (" + centerID + ") and  是否有效 =1 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

        #region 取分中心联动分站
        public DataTable GetCenterOnaspx(string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select 编码,名称 
                      from TCenter where 是否有效 =1 ");
            WhereClauseUtility.AddStringEqual("编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        public DataTable GetStationOnaspx(string centerID, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     select 编码,名称
                     from TStation  ");
            sb.Append("where 是否有效 = 1");
            WhereClauseUtility.AddInSelectQuery("中心编码", centerID, sb);
            WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 取药品名称
        public object GetDrugName()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     select im.Name from I_Material  im
                     where im.MTypeID in ('MaterialType-15','MaterialType-16') and im.IsActive=1 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["Name"].ToString();
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

        #region 分站暂停调用流水表 2016-11-09 周志猛
        //将“分中心暂停调用流水表”改为“分站暂停调用流水表” 2016-12-06 周志猛
        public DataTable Get_LS_FZXZTDY(DateTime beginTime, DateTime endTime,string station, string carNumber, string workCode, string name,
            E_StatisticsPermisson em, string selfWorkCode, string selfCenterID, string selfStationID, string eventDispatchCenterID)//去掉了“string center”
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                
                select 
	                 Center=tc.名称,
	                 Sation=ts.名称,
                     CarNumber=tam.实际标识,
                     RecordTime=tpr.操作时刻1,Operator1=tp1.姓名,
                     EndTime=tpr.操作时刻2,Operator2=tp2.姓名,
                     PauseTime=datediff(ss,tpr.操作时刻1,tpr.操作时刻2),
                     PauseReason=tzpr.名称,
                     DriverWorkNumber=tdriver.工号,
	                 Driver=tpr.司机
	                ,Doctor=tpr.医生,
                     Stretcher=tpr.担架工
                from (
                       select 
                       车辆编码=tp.车辆编码,
                       操作时刻1=tp.暂停时刻,
                       操作时刻2=min(tpr.恢复时刻),
                       暂停原因编码=tp.暂停原因编码,
                       tp.司机,tp.医生,tp.担架工
                       ,tp.暂停操作人员编码              
                      from ( 
                             select 车辆编码,暂停时刻,暂停原因编码,司机,医生,担架工
                             ,暂停操作人员编码  
                             from TPauseRecord   where 1=1 ");
            WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                             --where 是否暂停操作 = 1  
                            ) tp                             
                      left join (
                             select 车辆编码,恢复时刻,暂停原因编码,司机,医生,担架工
                              ,恢复操作人员编码        
                             from TPauseRecord   where 1=1 ");
            WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                             --where 是否暂停操作 = 0  
                                ) tpr on tpr.车辆编码=tp.车辆编码 and tpr.恢复时刻 > tp.暂停时刻
                      group by tp.车辆编码,tp.暂停时刻,tp.暂停原因编码,tp.司机,tp.医生,tp.担架工,tp.暂停操作人员编码
                   ) tpr 
                left join TAmbulance tam on tpr.车辆编码 = tam.车辆编码
                left join TStation ts on ts.编码=tam.分站编码
                left join TCenter tc on tc.编码=ts.中心编码
                left join TZPauseReason tzpr on tpr.暂停原因编码 = tzpr.编码
                left join TPerson tdriver on tdriver.编码 = tpr.暂停操作人员编码
                left join TPauseRecord tpau1 on tpau1.车辆编码=tpr.车辆编码 and tpau1.暂停时刻=tpr.操作时刻1
                left join TPerson tp1 on tp1.编码=tpau1.暂停操作人员编码
                left join TPauseRecord tpau2 on tpau2.车辆编码=tpr.车辆编码 and tpau2.暂停时刻=tpr.操作时刻2
                left join TPerson tp2 on tp2.编码=tpau2.暂停操作人员编码
                where tpr.操作时刻1>='" + beginTime + "' and tpr.操作时刻1<='" + endTime + @"' 
            ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2021-05-07 zch
            if (em == E_StatisticsPermisson.None)
                return null;

            else if (em == E_StatisticsPermisson.ALL)
            {
                //WhereClauseUtility.AddStringLike("tdriver.姓名", name, sb);
                //WhereClauseUtility.AddInSelectQuery("tc.编码", center, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddStringLike("tdriver.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("tam.实际标识", carNumber, sb);
                sb.Append("order by tc.顺序号,ts.顺序号,tpr.操作时刻1");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.CENTER)
            {
                //WhereClauseUtility.AddStringLike("tdriver.姓名", name, sb);
                WhereClauseUtility.AddStringEqual("tc.编码", selfCenterID, sb);
                WhereClauseUtility.AddInSelectQuery("ts.编码", station, sb);
                WhereClauseUtility.AddStringLike("tdriver.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("tam.实际标识", carNumber, sb);
                sb.Append("order by tc.顺序号,ts.顺序号,tpr.操作时刻1");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.STATION)
            {
                //WhereClauseUtility.AddStringLike("tdriver.姓名", name, sb);
                WhereClauseUtility.AddStringEqual("ts.编码", selfStationID, sb);
                WhereClauseUtility.AddStringLike("tdriver.工号", workCode, sb);
                WhereClauseUtility.AddStringLike("tam.实际标识", carNumber, sb);
                sb.Append("order by tc.顺序号,ts.顺序号,tpr.操作时刻1");

                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }


        #endregion

        #region 病历填写时间流水表
        public DataTable Get_LS_BLTXSJ(DateTime beginTime, DateTime endTime, string workCode, string centerID,
             string stationID, E_StatisticsPermisson em, string selfWorkCode, string selfCenterID, string selfStationID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                   select CallOrder=pr.CallOrder,
                   Name=pr.Name,
                   LocalAddress=pr.LocalAddress,
                   Driver=pr.Driver,
                   StretcherBearersI=pr.StretcherBearersI,                 
                   DoctorAndNurse=pr.DoctorAndNurse,
                   AgentName=pr.AgentName,
                   AgentWorkID=pr.AgentWorkID,                 
                   BeginFillPatientTime=pr.BeginFillPatientTime,
                   MedicalRecordGenerationTime=pr.MedicalRecordGenerationTime,
                   SubmitTime=pr.SubmitTime,
                   MedicalState=case when pr.MedicalStateCode = 0  then '暂存' 
                                     when pr.MedicalStateCode = 1  then '已提交' 
                                     when pr.MedicalStateCode = 2  then '未通过' 
                                     else '修改后提交' end
	    
                   from M_PatientRecord pr
                   left join P_Department d on d.DispatchSationID = pr.OutStationCode
                   where MedicalRecordGenerationTime>='" + beginTime + "' and  MedicalRecordGenerationTime<'" + endTime + "'");

            if (em == E_StatisticsPermisson.None)
                return null;

            else if (em == E_StatisticsPermisson.ALL)
            {
                WhereClauseUtility.AddStringEqual("pr.AgentWorkID", workCode, sb);
                WhereClauseUtility.AddInSelectQuery("d.DispatchSubCenterID", centerID, sb);
                WhereClauseUtility.AddInSelectQuery("d.DispatchSationID", stationID, sb);
                sb.Append("order by TaskCode");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.CENTER)
            {
                WhereClauseUtility.AddStringEqual("d.DispatchSubCenterID", selfCenterID, sb);
                WhereClauseUtility.AddInSelectQuery("d.DispatchSationID", stationID, sb);
                WhereClauseUtility.AddStringEqual("pr.AgentWorkID", workCode, sb);
                sb.Append("order by TaskCode");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.STATION)
            {
                WhereClauseUtility.AddStringEqual("d.DispatchSationID", selfStationID, sb);
                WhereClauseUtility.AddStringEqual("pr.AgentWorkID", workCode, sb);
                sb.Append("order by TaskCode");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else if (em == E_StatisticsPermisson.SELF)
            {
                sb.Append("and AgentWorkID = '" + selfWorkCode + @"'
                   order by TaskCode");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region  获取要车性质（事件类型）  （呼救事件流水表用）
        //获取要车性质（事件类型）
        public object GetAlarmEventType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select 编码,名称 from TZAlarmEventType where 是否有效=1
                        ");
            DataSet ds = (SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null));
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["编码"]);
                    info.Name = dr["名称"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

        #region  获取车辆任务状态 （呼救事件流水表用）
        public object GetCarState()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select 名称 into #temp from TZAmbulanceState where 是否有效=1
                    insert into #temp values('完成')
                    insert into #temp values('未出车')
                    select 名称 from #temp
                    drop table #temp
                        ");
            DataSet ds = (SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null));
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    // info.ID = Convert.ToString(dr["编码"]);
                    info.Name = dr["名称"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }



        #endregion

        #region 呼救事件流水表

        public DataTable Get_LS_HJSJ(DateTime beginTime, DateTime endTime, string alarmTypeCoding, string ambulanceState, string callNumber,
            string name, string ambulance, string driver, string doctor, string sceneAddress, string sendAddress, string illReason, string eventDispatchCenterID)
        {
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(@"            
                        select tae.事件编码,呼救电话=tac.呼救电话,往救地点=tac.现场地址,受理时间=tae.首次受理时刻
                        ,要车性质=tzaet.名称,呼救主诉=tac.主诉,车号=tam.实际标识
                        ,司机=isnull(dbo.GetStr(tt.任务编码,3),''),医生=isnull(dbo.GetStr(tt.任务编码,4),'')
                        ,tt.任务编码,任务状态=case when tt.是否执行中=0 then '完成' 
                        when tt.是否执行中=1 then tzas.名称 else '未出车' end,
                        任务状态编码=case when tt.是否执行中=0 then 10 when tt.是否执行中=1 then tzas.编码 else 11 end
                        into #temp1
                        from dbo.TAlarmEvent tae 
                        left join TAcceptEvent tac on tae.事件编码=tac.事件编码
                        left join dbo.TTask tt on tt.事件编码=tae.事件编码
                        left join dbo.TZAlarmEventType tzaet on tzaet.编码=tae.事件类型编码
                        left join dbo.TAmbulance tam on tam.车辆编码=tt.车辆编码
                        left join dbo.TZAmbulanceState tzas on tzas.编码=tam.工作状态编码
                        where tae.首次受理时刻>='" + beginTime + "' and tae.首次受理时刻<='" + endTime + @"' and tae.是否测试=0

                        and tt.任务编码>'" + taskCodeB + "' and tt.任务编码<='" + taskCodeE + @"'
                        and tae.事件编码>'" + eventCodeB + "' and tae.事件编码<='" + eventCodeE + @"' ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            WhereClauseUtility.AddInSelectQuery("tae.事件类型编码 ", alarmTypeCoding, sb);
            WhereClauseUtility.AddStringLike("tac.现场地址", sceneAddress, sb);
            WhereClauseUtility.AddStringLike("tac.送往地点", sendAddress, sb);
            WhereClauseUtility.AddStringLike("tac.呼救电话", callNumber, sb);
            WhereClauseUtility.AddStringEqual("tac.患者姓名", name, sb);
            WhereClauseUtility.AddStringLike("tac.主诉", illReason, sb);
            WhereClauseUtility.AddStringLike("tam.实际标识", ambulance, sb);

            sb.Append(@"select AlarmEventCode=事件编码,PhoneNumber=呼救电话,Address=往救地点,AcceptTime=受理时间,AlarmType=要车性质,
                               MainSuit=呼救主诉,CarNumber=车号,Driver=司机,Doctor=医生,TaskCode=任务编码,TaskState=任务状态,TaskStateCode=任务状态编码
                        from  #temp1 t1 
                        where 1=1");
            WhereClauseUtility.AddStringLike("司机", driver, sb);
            WhereClauseUtility.AddStringLike("医生", doctor, sb);
            WhereClauseUtility.AddInSelectQuery("任务状态编码", ambulanceState, sb);
            //WhereClauseUtility.AddStringEqual("任务状态", ambulanceState, sb);
            sb.Append(" order by 受理时间 desc ");
            sb.Append("  drop table #temp1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region 来电记录流水表 2016-11-04 周志猛
        public DataTable Get_LS_LDJL(DateTime beginTime, DateTime endTime, string callNumber, string actionResult, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"--set ansi_warnings off
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                                            
                        select 
                        来电时刻=呼入时刻,
                        主叫号码=对方电话,
                        调度员工号,姓名=tp.姓名,结束时刻,录音号
                        ,处理结果=case when 震铃时刻 is not null and 结果编码 in(1,2)  then '未接听' when 结果编码=4 then '已接听' else tztlr.名称 end
                        ,处理结果编码=case when 震铃时刻 is not null and 结果编码 in(1,2)  then 0 when 结果编码=4 then 1 else 2 end
                        into #temp
                        from dbo.TTelLog ttl 
                        left join TZTelLogResult tztlr on tztlr.编码=ttl.结果编码 
                        left join dbo.TPerson tp on tp.工号=ttl.调度员工号 
                        left join dbo.TDesk td on td.台号=ttl.台号 
                        where 呼入时刻 >= @BeginTime and 呼入时刻<=@EndTime 
                        --and 是否呼出=0  
                        ");
            WhereClauseUtility.AddStringEqual("ttl.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            //and tp.是否有效=1                       
            WhereClauseUtility.AddStringLike("主叫号码", callNumber, sb);

            sb.Append(@" select AlarmTime=来电时刻,PhoneNumber=主叫号码,WorkNumber=调度员工号,
                               Name=姓名,EndTime=结束时刻,Result=处理结果,RecordNumber=录音号,ResultCode=处理结果编码
                         from #temp 
                         where 1=1 ");
            WhereClauseUtility.AddInSelectQuery("处理结果编码", actionResult, sb);
            sb.Append(" order by 来电时刻 desc ");
            sb.Append(" drop table #temp ");
            //sb.Append(" set ansi_warnings on ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 取图表数据  日常急救到达率分段(月)  2016-11-10 周志猛
        public DataTable Get_LS_RCJJDDLFD_TuBiao(string year, string month, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); 

            sb.Append(@"SET ANSI_NULLS ON  
                        SET ANSI_WARNINGS ON 
                        "); //add2021-04-28 plq 解决异常：异类查询要求为连接设置 ANSI_NULLS 和 ANSI_WARNINGS 选项 
            sb.Append(@"                      
                        --set ansi_warnings off
                        select tt.任务编码, ale.首次受理时刻,tt.到达现场时刻
                        into #temp1
                        from dbo.TTask tt
                        inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                        join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                        left join TStation ts on tt.分站编码=ts.编码
                        where datepart(yy,首次受理时刻)=datepart(yy,dateadd(m,-1,convert(datetime,convert(varchar(4),'" + year + "')+'-'+convert(varchar(2),'" + month + @"')+'-01')))
                        and datepart(mm,首次受理时刻)=datepart(mm,dateadd(m,-1,convert(datetime,convert(varchar(4),'" + year + "')+'-'+convert(varchar(2),'" + month + @"')+'-01')))
                        and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                        and 事件类型编码 in (@救治,@回家,@转院) ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch           
            sb.Append(@"
                        --and ts.中心编码<>1
                        select  tt.任务编码, ale.首次受理时刻,tt.到达现场时刻
                        into #temp2
                        from dbo.TTask tt
                        inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                        join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                        left join TStation ts on tt.分站编码=ts.编码
                        where datepart(yy,首次受理时刻)='" + year + @"'
                        and datepart(mm,首次受理时刻)='" + month + @"'
                        and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                        and 事件类型编码 in (@救治,@回家,@转院)    ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                        --and ts.中心编码<>1

                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='总次数',
                        数量=count(*)
                        ,顺序号=-1
                        into #temp
                        from #temp1
                        group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='总次数',
                        数量=count(*)
                        ,顺序号=0
                        from #temp2
                        group by datepart(mm,首次受理时刻)
                        union
                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='10分钟内',
                        数量=count(*)
                        ,顺序号=1
                        from #temp1
                        where datediff(second,首次受理时刻,到达现场时刻)<=600 group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='10分钟内',
                        数量=count(*)
                        ,顺序号=2
                        from #temp2
                        where datediff(second,首次受理时刻,到达现场时刻)<=600 group by datepart(mm,首次受理时刻)
                        union
                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='10-12分钟',
                        数量=count(*)
                        ,顺序号=3
                        from #temp1
                        where datediff(second,首次受理时刻,到达现场时刻)>600 and datediff(second,首次受理时刻,到达现场时刻)<=720 group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='10-12分钟',
                        数量=count(*)
                        ,顺序号=4
                        from #temp2
                        where datediff(second,首次受理时刻,到达现场时刻)>600 and datediff(second,首次受理时刻,到达现场时刻)<=720 group by datepart(mm,首次受理时刻)
                        union
                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='12-15分钟',
                        数量=count(*)
                        ,顺序号=5
                        from #temp1
                        where datediff(second,首次受理时刻,到达现场时刻)>720 and datediff(second,首次受理时刻,到达现场时刻)<=900 group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='12-15分钟',
                        数量=count(*)
                        ,顺序号=6
                        from #temp2
                        where datediff(second,首次受理时刻,到达现场时刻)>720 and datediff(second,首次受理时刻,到达现场时刻)<=900 group by datepart(mm,首次受理时刻)
                        union
                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='15-20分钟',
                        数量=count(*)
                        ,顺序号=7
                        from #temp1
                        where datediff(second,首次受理时刻,到达现场时刻)>900 and datediff(second,首次受理时刻,到达现场时刻)<=1200 group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='15-20分钟',
                        数量=count(*)
                        ,顺序号=8
                        from #temp2
                        where datediff(second,首次受理时刻,到达现场时刻)>900 and datediff(second,首次受理时刻,到达现场时刻)<=1200 group by datepart(mm,首次受理时刻)
                        union
                        select 
                        序列=datepart(mm,首次受理时刻),
                        类别='20分钟以上',
                        数量=count(*)
                        ,顺序号=9
                        from #temp1
                        where datediff(second,首次受理时刻,到达现场时刻)>1200 group by datepart(mm,首次受理时刻)
                        union 
                        select
                        序列=datepart(mm,首次受理时刻),
                        类别='20分钟以上',
                        数量=count(*)
                        ,顺序号=10
                        from #temp2
                        where datediff(second,首次受理时刻,到达现场时刻)>1200 group by datepart(mm,首次受理时刻)

                        select XuLie=序列,NeiBie=类别,Number=数量,SN=顺序号 from #temp order by 顺序号

                        drop table #temp1,#temp2
                        drop table #temp
            ");
            sb.Append(@"
                        SET ANSI_NULLS OFF
                        SET ANSI_WARNINGS OFF
                        "); //add2021-04-28 plq 解决异常：异类查询要求为连接设置 ANSI_NULLS 和 ANSI_WARNINGS 选项 
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];

        }
        #endregion

        #region 日常急救到达率分段（月）流水表 2106-11-10 周志猛
        public DataTable Get_LS_RCJJDDLFD(string year, string month, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); 

            sb.Append(@"
                        --set ansi_warnings off  
                        set nocount on                   
                        select 
                        --Center=tc.名称,
                        AlarmEventType=alet.名称,
                        TotalTimes=count(*),
                        TimesIn10Minute=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=600 then 1 else 0 end)
                        ,TimesBetween10And12Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>600 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=720 then 1 else 0 end)
                        ,TimesBetween12And15Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>720 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=900 then 1 else 0 end)
                        ,TimesBetween15And20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>900 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=1200 then 1 else 0 end)
                        ,TimesOver20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>1200 then 1 else 0 end)
                        from dbo.TTask tt
                        inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                        join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                        left join dbo.TZAlarmEventType alet on alet.编码=ale.事件类型编码
                        left join TStation ts on tt.分站编码=ts.编码
                        --left join TCenter tc on ts.中心编码=tc.编码
                        where datepart(yy,首次受理时刻)='" + year + "' and datepart(mm,首次受理时刻)='" + month + @"'
                        and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                        and 事件类型编码 in (@救治,@回家,@转院)  ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                        --and ts.中心编码<>1
                        group by 
                        --tc.名称,
                        alet.名称
                        order by 
                        --tc.名称,
                        alet.名称
                        set nocount off
                        --set ansi_warnings on
              ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        public DataTable Get_LS_RCJJDDLFDSum(string year, string month, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); 

            sb.Append(@"
                        set nocount on                 
                        select 
                        SumAlarmEventType=alet.名称,
                        SumTotalTimes=count(*),
                        SumTimesIn10Minute=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=600 then 1 else 0 end)
                        ,SumTimesBetween10And12Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>600 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=720 then 1 else 0 end)
                        ,SumTimesBetween12And15Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>720 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=900 then 1 else 0 end)
                        ,SumTimesBetween15And20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>900 and datediff(second,ale.首次受理时刻,tt.到达现场时刻)<=1200 then 1 else 0 end)
                        ,SumTimesOver20Minutes=sum(case when datediff(second,ale.首次受理时刻,tt.到达现场时刻)>1200 then 1 else 0 end)
                        from dbo.TTask tt
                        inner join dbo.TAmbulanceStateTime tast on tt.任务编码=tast.任务编码
                        join dbo.TAlarmEvent ale on tt.事件编码=ale.事件编码
                        left join dbo.TZAlarmEventType alet on alet.编码=ale.事件类型编码
                        left join TStation ts on tt.分站编码=ts.编码
                        where datepart(yy,首次受理时刻)='" + year + "' and datepart(mm,首次受理时刻)='" + month + @"'
                        and tt.到达现场时刻 is not null and tast.车辆状态编码=3 and 操作来源编码=2 and ale.是否测试=0
                        and 事件类型编码 in (@救治,@回家,@转院)   ");
            WhereClauseUtility.AddStringEqual("ale.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                        and ts.中心编码<>1
                        group by alet.名称
                        order by alet.名称
                        set nocount off
                        
                    ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  受理记录流水表
        public DataTable Get_LS_SLJL(DateTime beginTime, DateTime endTime, string acceptType, string callType, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            if (acceptType == "" && callType == "")
            {
                sb.Append(@"
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        DECLARE @acceptType varchar
                        DECLARE @callType varchar
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                        set @acceptType = '" + acceptType + @"'
                        set @callType = '" + callType + @"'
       
                       select * from(
                        select top 10000000 CallTime=tac.通话时刻,CallNumber=tac.主叫号码,AcceptType=tzaet.名称
                        ,CallCode=tac.事件编码,WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCall tac
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=tac.通话类型编码
                        left join dbo.TPerson tp on tp.编码=tac.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("tac.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                //sb.Append(@" and tzaet.编码 in( @acceptType)");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco.通话时刻,CallNumber=taco.主叫号码,AcceptType=tzct.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco
                        left join dbo.TZCallType tzct on tzct.编码=taco.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco.通话类型编码<=10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzct.编码", callType, sb);
                //sb.Append(@"  and tzct.编码 in(@callType) ");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco2.通话时刻,CallNumber=taco2.主叫号码,AcceptType=tzaet.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco2
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=taco2.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco2.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco2.通话类型编码>10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco2.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                //sb.Append(@" and tzaet.编码 in( @acceptType)");

                sb.Append("  ) as A ");
                sb.Append("order by CallTime ");
            }
            else if (acceptType == "" && callType != "")
            {
                sb.Append(@"
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        DECLARE @acceptType varchar
                        DECLARE @callType varchar
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                        set @acceptType = '" + acceptType + @"'
                        set @callType = '" + callType + @"'
       
                       select * from(
                        select top 10000000 CallTime=tac.通话时刻,CallNumber=tac.主叫号码,AcceptType=tzaet.名称
                        ,CallCode=tac.事件编码,WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCall tac
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=tac.通话类型编码
                        left join dbo.TPerson tp on tp.编码=tac.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("tac.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@" and tzaet.编码 in( 1000)");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco.通话时刻,CallNumber=taco.主叫号码,AcceptType=tzct.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco
                        left join dbo.TZCallType tzct on tzct.编码=taco.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco.通话类型编码<=10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzct.编码", callType, sb);
                //sb.Append(@"  and tzct.编码 in(@callType) ");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco2.通话时刻,CallNumber=taco2.主叫号码,AcceptType=tzaet.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco2
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=taco2.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco2.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco2.通话类型编码>10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco2.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@" and tzaet.编码 in( 1000)");

                sb.Append("  ) as A ");
                sb.Append("order by CallTime ");
            }
            else if (acceptType != "" && callType == "")
            {
                sb.Append(@"
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        DECLARE @acceptType varchar
                        DECLARE @callType varchar
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                        set @acceptType = '" + acceptType + @"'
                        set @callType = '" + callType + @"'
       
                       select * from(
                        select top 10000000 CallTime=tac.通话时刻,CallNumber=tac.主叫号码,AcceptType=tzaet.名称
                        ,CallCode=tac.事件编码,WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCall tac
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=tac.通话类型编码
                        left join dbo.TPerson tp on tp.编码=tac.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("tac.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                //sb.Append(@" and tzaet.编码 in( @acceptType)");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco.通话时刻,CallNumber=taco.主叫号码,AcceptType=tzct.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco
                        left join dbo.TZCallType tzct on tzct.编码=taco.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco.通话类型编码<=10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                sb.Append(@"  and tzct.编码 in(1000) ");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco2.通话时刻,CallNumber=taco2.主叫号码,AcceptType=tzaet.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco2
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=taco2.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco2.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco2.通话类型编码>10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco2.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                //sb.Append(@" and tzaet.编码 in( @acceptType)");

                sb.Append("  ) as A ");
                sb.Append("order by CallTime ");
            }
            else if (acceptType != "" && callType != "")
            {
                sb.Append(@"
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        DECLARE @acceptType varchar
                        DECLARE @callType varchar
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                        set @acceptType = '" + acceptType + @"'
                        set @callType = '" + callType + @"'
       
                       select * from(
                        select top 10000000 CallTime=tac.通话时刻,CallNumber=tac.主叫号码,AcceptType=tzaet.名称
                        ,CallCode=tac.事件编码,WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCall tac
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=tac.通话类型编码
                        left join dbo.TPerson tp on tp.编码=tac.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("tac.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                //sb.Append(@" and tzaet.编码 in( @acceptType)");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco.通话时刻,CallNumber=taco.主叫号码,AcceptType=tzct.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco
                        left join dbo.TZCallType tzct on tzct.编码=taco.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco.通话类型编码<=10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzct.编码", callType, sb);
                // sb.Append(@"  and tzct.编码 in(@callType) ");
                sb.Append(" union ");
                sb.Append(@" select top 10000000 CallTime=taco2.通话时刻,CallNumber=taco2.主叫号码,AcceptType=tzaet.名称
                        ,CallCode='',WorkCode=tp.工号,RecordCode=录音号
                        from dbo.TAlarmCallOther taco2
                        left join dbo.TZAcceptEventType tzaet on tzaet.编码=taco2.通话类型编码
                        left join dbo.TPerson tp on tp.编码=taco2.调度员编码
                        where 通话时刻>=@BeginTime and 通话时刻<=@EndTime
                        and taco2.通话类型编码>10 and tp.是否有效=1 ");
                WhereClauseUtility.AddStringEqual("taco2.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
                WhereClauseUtility.AddInSelectQuery("tzaet.编码", acceptType, sb);
                // sb.Append(@" and tzaet.编码 in( @acceptType)");

                sb.Append("  ) as A ");
                sb.Append("order by CallTime ");
            }
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region 司机出车大于5分钟流水表 2016-11-09 周志猛
        public DataTable Get_LS_SJCCQK(DateTime beginTime, DateTime endTime, string station, string name, string workCode, string carNumber, int sendCarTime, string eventDispatchCenterID)// string center
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@" --set ansi_warnings off
                        DECLARE @BeginTime DATETIME
                        DECLARE @EndTime datetime
                        SET @BeginTime = '" + beginTime + @"'
                        SET @EndTime = '" + endTime + @"'
                        --declare @s int
                        --set @s=5

                        declare @EventCodeB char(18)
                        declare @EventCodeE char(18)
                        declare @TaskCodeB char(22)
                        declare @TaskCodeE char(22)

                        set @EventCodeB = convert(char(8),@BeginTime,112)+'00000000'
                        set @EventCodeE = convert(char(8),dateadd(day,1,@EndTime),112)+'00000000'
                        set @TaskCodeB = @EventCodeB+'0000'
                        set @TaskCodeE = @EventCodeE+'0000'



                        select tast.任务编码,操作来源编码, 车辆状态编码
                        into #temptime
                        from TAmbulanceStateTime tast
                        left join TAmbulance ta on tast.车辆编码 = ta.车辆编码
                        left join TStation ts on ta.分站编码 = ts.编码
                        where tast.任务编码>@TaskCodeB and tast.任务编码<=@TaskCodeE ");
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"

                        --select 任务编码,收到指令方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        --into #temp1
                        --from #temptime
                        --where 车辆状态编码=1
                        select 任务编码,驶向现场方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        into #temp2
                        from #temptime
                        where 车辆状态编码=2
                        select 任务编码,抢救转运方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        into #temp3
                        from TAmbulanceStateTime 
                        where 车辆状态编码=3
                        select 任务编码,病人上车方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        into #temp4
                        from #temptime
                        where 车辆状态编码=4
                        select 任务编码,到达医院方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        into #temp5
                        from #temptime
                        where 车辆状态编码=5
                        select 任务编码,途中待命方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '其他' end
                        into #temp6
                        from #temptime
                        where 车辆状态编码=6

                        select tt.任务编码,驶向现场方式,抢救转运方式,病人上车方式,到达医院方式,途中待命方式
                        into #temp7
                        from TTask tt  
                        left join TAlarmEvent tae on tt.事件编码=tae.事件编码
                        --left join #temp1 t1 on t1.任务编码=tt.任务编码
                        left join #temp2 t2 on t2.任务编码=tt.任务编码
                        left join #temp3 t3 on t3.任务编码=tt.任务编码
                        left join #temp4 t4 on t4.任务编码=tt.任务编码
                        left join #temp5 t5 on t5.任务编码=tt.任务编码
                        left join #temp6 t6 on t6.任务编码=tt.任务编码
                        where tt.任务编码>@TaskCodeB and tt.任务编码<=@TaskCodeE ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"


                        select
                         TaskCode=tt.任务编码,
                       --Center=tc.名称,
                        Station=ts.名称,
                        CarNumber=tam.实际标识,
                        Driver=tp.姓名,
                        AskTime=convert(varchar(20),tt.生成任务时刻,120),
                        SendTime=convert(varchar(20),tt.出车时刻,120),
                        ArriveScenesTime=convert(varchar(20),tt.到达现场时刻,120),
                        PaientInCarTime=convert(varchar(20),tt.离开现场时刻,120),
                        ArriveHospitalTime=convert(varchar(20),tt.到达医院时刻,120),
                        FinishMissionTime=convert(varchar(20),tt.完成时刻,120),
                        keyType=case when  驶向现场方式='台' and 抢救转运方式='台' 
                        and 病人上车方式='台' and 到达医院方式='台' and 途中待命方式='台' then '调度'
                        when  驶向现场方式='车载' and 抢救转运方式='车载' 
                        and 病人上车方式='车载' and 到达医院方式='车载' and 途中待命方式='车载' then 'GPS'
                        else '其他' end ,
                        Time='" + sendCarTime + @"'
                        ,TaskRunCode=tt.任务流水号
                        ,Dispatcher=tpe.姓名
  
                        from TTask tt
                        left join TAlarmEvent tae on tae.事件编码=tt.事件编码
                        left join TAmbulance tam on tam.车辆编码=tt.车辆编码
                        left join TStation ts on ts.编码=tt.分站编码
                        --left join TCenter tc on tc.编码=ts.中心编码
                        left join TTaskPersonLink ttpl on ttpl.任务编码=tt.任务编码 and ttpl.人员类型编码=3
                        left join TPerson tp on tp.编码=ttpl.人员编码
                        left join TPerson tpe on tpe.编码=tt.责任调度人编码
                        left join #temp7 ttt on ttt.任务编码=tt.任务编码

                        where 生成任务时刻>=@BeginTime and 生成任务时刻<=@EndTime 
                        and tt.任务编码>@TaskCodeB and tt.任务编码<=@TaskCodeE
                        and tt.是否正常结束=1 and tt.是否执行中=0 and tae.是否测试=0 ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            if (sendCarTime > 0)
            { sb.Append("  and datediff(second,tt.生成任务时刻,isnull(出车时刻,DATEADD(SECOND,1 ,CONVERT(datetime,tt.生成任务时刻,120))))>'" + sendCarTime + @"'*60 "); }
            WhereClauseUtility.AddStringLike("tp.姓名", name, sb);
            //WhereClauseUtility.AddInSelectQuery("ts.中心编码", center, sb);
            WhereClauseUtility.AddInSelectQuery("tt.分站编码", station, sb);
            WhereClauseUtility.AddStringLike("tp.工号", workCode, sb);
            WhereClauseUtility.AddStringLike("tam.实际标识", carNumber, sb);

            sb.Append(@"
                        order by 
                        --tc.顺序号,
                        ts.名称,tam.实际标识,tp.姓名,tt.生成任务时刻
                        drop table #temptime                      
                        drop table #temp2
                        drop table #temp3
                        drop table #temp4
                        drop table #temp5
                        drop table #temp6
                        drop table #temp7
                        --set ansi_warnings on
                  ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 病历流水表
        public DataTable Get_LS_BL(DateTime beginTime, DateTime endTime, string eventType, string name, string centerID, string stationID
            , string diseasesClassification, string doctorAndNurse, string driver, string stretcher, string alarmReason,
             string illnessClassification, string illnessForecast, string firstAidEffect, string diseaseCooperation
            , string firstImpression, string deathCase, string deathCertificate, string treatmentMeasure)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                  select 
                         PatientVersion= mpr.PatientVersion
                         ,Name=mpr.Name
                        ,Sex=mpr.Sex
                        ,AgeType=mpr.AgeType,
                         Age= case when AgeType = '不详' then '不详' when PatientVersion in ('空车','取暖箱') then '' else Age+AgeType  end 
                        ,FirstCallTime=tae.首次受理时刻
                        , X=tae.X坐标
                        ,Y=tae.Y坐标
                        ,Station=mpr.Station
                        ,LocalAddress=mpr.LocalAddress
                        ,DrivingTime=mpr.DrivingTime
                        ,ArriveSceneTime=mpr.ArriveSceneTime
                        ,SendAddress=mpr.SendAddress
                        ,LeaveSceneTime=mpr.LeaveSceneTime
                        ,ArriveDestinationTime=mpr.ArriveDestinationTime
                        ,DoctorAndNurse=mpr.DoctorAndNurse
                        ,TeachingPractice=mpr.TeachingPractice
                        ,Driver=mpr.Driver
                        ,StretcherBearersI=mpr.StretcherBearersI
                        ,ProvideMedicalHistoryPeople=mpr.ProvideMedicalHistoryPeople
                        ,DiseasesClassification=mpr.DiseasesClassification
                        ,AlarmReason=mpr.AlarmReason
                        ,ContactTelephone=mpr.ContactTelephone
                        ,HistoryOfPresentIllness=mpr.HistoryOfPresentIllness
                        ,SaveOneselfMeasures=mpr.SaveOneselfMeasures
                        ,SaveOneselfMeasuresSupplement=mpr.SaveOneselfMeasuresSupplement,
                        PastMedicalHistory=mpr.PastMedicalHistory,PastMedicalHistorySupplement=mpr.PastMedicalHistorySupplement,TChoose=mpra.TChoose
                        ,T=mpra.T,PChoose=mpra.PChoose,P=mpra.P,RChoose=mpra.RChoose,R=mpra.R,BPChoose=mpra.BPChoose,BP1=mpra.BP1,BP2=mpra.BP2,BP3=mpra.BP3,BP4=mpra.BP4,Consciousness=mpra.Consciousness
                        ,Pupilla=mpra.Pupilla,PupillaSupplement=mpra.PupillaSupplement,LightReflex=mpra.LightReflex,LightReflexSupplement=mpra.LightReflexSupplement,Skin=mpra.Skin,SkinSupplement=mpra.SkinSupplement
                        ,Head=mpra.Head,HeadSupplement=mpra.HeadSupplement,Neck=mpra.Neck,NeckSupplement=mpra.NeckSupplement,Chest=mpra.Chest,ChestExtrusionTest=mpra.ChestExtrusionTest,ChestSupplement=mpra.ChestSupplement
                        ,Lungs=mpra.Lungs,TwoLungBreathingSound=mpra.TwoLungBreathingSound,LeftLung=mpra.LeftLung,RightLung=mpra.RightLung,LungsSupplement=mpra.LungsSupplement,Heart=mpra.Heart,HeartRate=mpra.HeartRate
                        ,HeartRhythm=mpra.HeartRhythm,HeartMurmur=mpra.HeartMurmur,HeartSupplement=mpra.HeartSupplement,Abdomen=mpra.Abdomen,AbdomenSupplement=mpra.AbdomenSupplement,Spine=mpra.Spine
                        ,SpineSupplement=mpra.SpineSupplement,Limbs=mpra.Limbs,LimbsSupplement=mpra.LimbsSupplement,PelvicExtrusionTest=mpra.PelvicExtrusionTest,NervousSystem=mpra.NervousSystem
                        ,NervousSystemFace=mpra.NervousSystemFace,NervousSystemSpeech=mpra.NervousSystemSpeech,NervousSystemSupplement=mpra.NervousSystemSupplement,LeftUpperExtremity=mpra.LeftUpperExtremity
                        ,LeftLowerExtremity=mpra.LeftLowerExtremity,RightUpperLimb=mpra.RightUpperLimb,RightLowerLimb=mpra.RightLowerLimb,BabinskiSign=mpra.BabinskiSign,ObstetricExamination=mpra.ObstetricExamination
                        ,GongGaoCartilagoEnsiformis=mpra.GongGaoCartilagoEnsiformis,GongGaoNavel=mpra.GongGaoNavel,GongGaoSuprapubic=mpra.GongGaoSuprapubic,GongGaoBelowUmbilicus=mpra.GongGaoBelowUmbilicus
                        ,ObstetricExaminationSupplement=mpra.ObstetricExaminationSupplement,OpenReaction=mpra.OpenReaction,LanguageReaction=mpra.LanguageReaction,MotionResponse=mpra.MotionResponse,Position=mpra.Position
                        ,DamageWay=mpra.DamageWay,CirculationChange=mpra.CirculationChange,BreathingChange=mpra.BreathingChange,ConsciousnessChange=mpra.ConsciousnessChange,HeartRatePerMinute=mpra.HeartRatePerMinute
                        ,Breathing=mpra.Breathing,MuscleTension=mpra.MuscleTension,LaryngealReflex=mpra.LaryngealReflex,SkinColor=mpra.SkinColor,SymptomPendingInvestigation=mpra.SymptomPendingInvestigation
                        ,SymptomPendingInvestigationSupplement=mpra.SymptomPendingInvestigationSupplement,FirstImpression=mpra.FirstImpression+mpra.FirstImpressionDoubt,FirstImpressionSupplement=mpra.FirstImpressionSupplement
                        ,ECGImpression=mpra.ECGImpression+mpra.ECGImpressionDoubt,ECGImpressionSupplement=mpra.ECGImpressionSupplement,ECGImpressionRetestI=mpra.ECGImpressionRetestI+mpra.ECGImpressionRetestIDoubt
                        ,ECGImpressionRetestISupplement=mpra.ECGImpressionRetestISupplement,ECGImpressionRetestII=mpra.ECGImpressionRetestII+mpra.ECGImpressionRetestIIDoubt,
                        ECGImpressionRetestIISupplement=mpra.ECGImpressionRetestIISupplement,BloodSugar=mpra.BloodSugar,BloodSugarRetestI=mpra.BloodSugarRetestI
                        ,BloodSugarRetestII=mpra.BloodSugarRetestII,BloodOxygenSaturation=mpra.BloodOxygenSaturation,BloodOxygenSaturationRetestI=mpra.BloodOxygenSaturationRetestI,BloodOxygenSaturationRetestII=mpra.BloodOxygenSaturationRetestII
                        ,CPRIFSuccess=mpr.CPRIFSuccess,IllnessClassification=mpr.IllnessClassification,IllnessForecast=mpr.IllnessForecast,DeathCase=mpr.DeathCase,DeathCertificate=mpr.DeathCertificate,FirstAidEffect=mpr.FirstAidEffect
                        ,MajorEmergencies=mpr.MajorEmergencies,DiseaseCooperation=mpr.DiseaseCooperation,DiseaseNotCooperationSupplement=mpr.DiseaseNotCooperationSupplement,Witness=mprc.Witness,CarToBeforeCPR=mprc.CarToBeforeCPR
                        ,CarToBeforeDefibrillation=mprc.CarToBeforeDefibrillation,CardiacArrestReason=mprc.CardiacArrestReason,CardiacArrestReasonSupplement=mprc.CardiacArrestReasonSupplement
                        ,AfterResuscitationECGDiagnosis=mprc.AfterResuscitationECGDiagnosis,AfterResuscitationBP=mprc.AfterResuscitationBP,AfterResuscitationSaO2=mprc.AfterResuscitationSaO2,PulsationAppearTime= mprc.PulsationAppearTime
                        ,BreatheAppearTime=mprc.BreatheAppearTime,IFAdmittedToHospital=mprc.IFAdmittedToHospital,DoctorFollowUp=mprc.DoctorFollowUp,DoctorFollowUpReason=mprc.DoctorFollowUpReason,
                        AttackPlace=mprc.AttackPlace,ArrivingTime=mprc.ArriveSceneTime,ChestCompression=mprc.ChestCompression,StartChestCompressionTime=mprc.StartChestCompressionTime,BeforeResuscitationECGDiagnosis=mprc.BeforeResuscitationECGDiagnosis,
                        Defibrillation=mprc.Defibrillation,FirstDefibrillationTime=mprc.FirstDefibrillationTime,IntervalTime=mprc.IntervalTime,PhysicalExaminationSupplement=mpra.PhysicalExaminationSupplement
                                  
                   from  M_PatientRecord mpr 
                   left join  M_PatientRecordAppend mpra on mpr.TaskCode = mpra.TaskCode
                   left join  M_PatientRecordCPR  mprc on mpr.TaskCode = mprc.TaskCode ");
            sb.Append("left join ").Append(DispatchBuilder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append("left join ").Append(DispatchBuilder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append("left join ").Append(DispatchBuilder.InitialCatalog).Append(".dbo.TAlarmEvent tae on tae.事件编码=tt.事件编码 ");
            sb.Append(" where tt.生成任务时刻>='" + beginTime + "' and tt.生成任务时刻<'" + endTime + @"' and mpr.SubmitLogo=1 ");
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);
            WhereClauseUtility.AddStringEqual("mpr.PatientVersion", eventType, sb);
            WhereClauseUtility.AddStringLike("mpr.DiseasesClassification", diseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.Driver", driver, sb);
            WhereClauseUtility.AddStringEqual("mpr.Name", name, sb);
            WhereClauseUtility.AddStringLike("mpr.DoctorAndNurse", doctorAndNurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.StretcherBearersI", stretcher, sb);
            WhereClauseUtility.AddStringLike("mpr.AlarmReason", alarmReason, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", illnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessForecast", illnessForecast, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", firstAidEffect, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseaseCooperation", diseaseCooperation, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", firstImpression, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", deathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCertificate", deathCertificate, sb);
            WhereClauseUtility.AddStringLike("mpr.TreatmentMeasure", treatmentMeasure, sb);

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 取分站（病历流水表）
        //取分站
        public object GetStations(string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select 编码,名称 
                      from TStation  where 是否有效 =1 ");
            WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取病种类型（病历流水表）
        //取病种类型
        public object GetDiseasesClassifications()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_ZCaseTemplate  where IsActive =1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取病情类型（病历流水表）
        public object GetIllnessClassification()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'IllState' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取病情预报（病历流水表）
        public object GetIllnessForecast()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'IllStateReport' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取急救效果（病历流水表）
        public object GetFirstAidEffect()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'FirstAidEffect' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取病家合作度（病历流水表）
        public object GetDiseaseCooperation()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'DiseaseCooperation' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取事件类型（病历流水表）
        public object GetEventType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'PatientVersion' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取死亡类型(病历流水表)
        public object GetDeathCase()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'DeathCase' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取死亡证明类型(病历流水表)
        public object GetDeathCertificate()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select ID,Name 
                      from M_Dictionary  where IsActive = 1 and TypeID = 'DeathCertificate' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = Convert.ToString(dr["ID"]);
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取受理类型

        public object GetAcceptType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select  编码,名称 from TZAcceptEventType
                        where 是否有效=1                 
                        ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        //取电话类型
        public object GetCallType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZCallType
                        where 是否有效=1 and 编码 in (0,4,10)");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取车辆状态类型

        public object GetAmbulanceState()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select  编码,名称 from TZAmbulanceState
                        where 是否有效=1                 
                        ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取车辆状态类型

        public object GetRole()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select  编码,名称 from TRole
                        where 是否有效=1  and 编码 in (3,4,5,6)               
                        ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<P_User> list = new List<P_User>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                P_User info = new P_User();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new P_User();
                    info.ID = Convert.ToInt32(dr["编码"]);
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 病历收费流水表
        //2017-11-09 增加字段 PaidCarFee,PaidPRFee
        //20210513 gdg 增加判断ChargeType 医保等,是否审核算法
        //20210620--gdg--增加收费方式显示抹零实收(分币误差)
        //20210625--gdg--增加列“现金实收”、“分币误差”、“支付宝实收”、“微信实收”、“医保实收”
        //20210629--gdg--修改查询时间为收费时间,修改现金实收合计算法（有异常数据，如果收费主表类型为微信,支付宝或者银行转账，收费子表是现金的，就不算到现金合计里）
        //20210701--gdg--增加判断如果查询医保，就关联医保明细表根据医保交易时间查询,并且增加IFYiBaoTime判断是否根据医保时间来查询
        //20210705--gdg--修改分币误差合计算法
        //20210711--gdg--增加判断如果选择医保时间查询的时候，再判断收费子表的收费时间
        //20210713--gdg--增加判断如果选择医保时间查询的时候，也取医保表的退款数据
        //20211015--plq--医保上线移植 新增收费方式、支付宝微信审核、是否医保时间三条件，移植医保收费相关字段
        //20211026--zll--医保上线新增郊区一车多人现象处理，新增病历号
        public DataTable Get_LS_PatientCharge(DateTime beginTime, DateTime endTime, string eventType, string stationID, string agentID, string doctorAndNurse,
          string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtFirstAidEffect,
         string txtFirstImpression, string IFNormalEnd, string OrderByWay, string StretcherBearersI, string Driver, string DriverWC, string DoctorWC, string StretcherBearersWC
          , int chargeType, string IFAccountCheck, int IFYiBaoTime)
        {
            StringBuilder sb = new StringBuilder();
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            SqlConnectionStringBuilder builderyb = new SqlConnectionStringBuilder(SqlHelper.YBConnectionString); //add2021-10-13 plq 医保上线移植
            sb.Append("declare @BeginTime datetime ");
            sb.Append("declare @EndTime datetime ");
            sb.Append("set @BeginTime='" + Convert.ToDateTime(beginTime) + "' ");
            sb.Append("set @EndTime ='" + Convert.ToDateTime(endTime) + "' ");
            sb.Append("declare @EventCodeB char(16) ");
            sb.Append("declare @EventCodeE char(16) ");
            sb.Append("declare @TaskCodeB  char(20) ");
            sb.Append("declare @TaskCodeE  char(20) ");
            sb.Append("set @EventCodeB = convert(char(8),@BeginTime,112)+'00000000' ");
            sb.Append("set @EventCodeE = convert(char(8),dateadd(day,1,@EndTime),112)+'00000000' ");
            sb.Append("set @TaskCodeB = @EventCodeB+'0000' ");
            sb.Append("set @TaskCodeE = @EventCodeE+'0000' ");
            //20210701
            if (IFYiBaoTime == 1)
            {
                sb.Append(@"
               select
			   任务编码,病历序号,交易时间=max(交易时间)
			   into #temp3
                from ").Append(builderyb.InitialCatalog).Append(@".dbo.M_PatientRecordYiBao mpryb 
                where mpryb.交易时间 >=@BeginTime and mpryb.交易时间 <=@EndTime --and mpryb.操作状态=3
			    group by 任务编码,病历序号 ");

            }
            sb.Append(@"
				   select distinct 
                  m.TaskCode as TaskCode,m.PatientOrder as PatientOrder,

                (select  CONVERT(varchar(20),(case when mpcd.ChargeType=0 then '现金(' + convert(varchar(20),mpcd.PaidMoney) + ')' 
				    when mpcd.ChargeType=1 then '支付宝(' + convert(varchar(20),mpcd.PaidMoney) + ')' 
                     when mpcd.ChargeType=2 then '微信(' + convert(varchar(20),mpcd.PaidMoney) + ')'
				     when mpcd.ChargeType=3 then '银行转账(' + convert(varchar(20),mpcd.PaidMoney) + ')'
                      when mpcd.ChargeType=4 then '医保(' + convert(varchar(20),mpcd.PaidMoney) + ')'
                      when mpcd.ChargeType=5 then '医保退款(' + convert(varchar(20),mpcd.PaidMoney) + ')'
                      when mpcd.ChargeType=6 then '离休(' + convert(varchar(20),mpcd.PaidMoney) + ')'
                      when mpcd.ChargeType=7 then '分币误差(' + convert(varchar(20),mpcd.PaidMoney) + ')'  end)) +',' 
                
                from M_PatientCharge mpc 
                left join M_PatientChargeDetail mpcd on mpc.TaskCode = mpcd.TaskCode and mpc.PatientOrder = mpcd.PatientOrder ");
            //20210701add--gdg
            if (IFYiBaoTime == 1)
            {
                sb.Append(@"
                   left join #temp3 mpryb on mpc.TaskCode = mpryb.任务编码 and mpc.PatientOrder = mpryb.病历序号
                    --where mpc.Date >=@BeginTime and mpc.Date <=@EndTime
			       where mpryb.交易时间 >=@BeginTime and mpryb.交易时间 <=@EndTime
                         and mpcd.ChargeDate >=@BeginTime and mpcd.ChargeDate <=@EndTime ");//20210711--gdg
            }
            else
            {
                sb.Append(@"
                  where mpc.Date >=@BeginTime and mpc.Date <=@EndTime ");
            }
            sb.Append(@"
                   and mpc.TaskCode=m.TaskCode FOR XML PATH('')) as 收费类型
                  ,是否审核=max(case when m.[IFAccountCheck]=1 then 1 else 0 end) 
                  --,微信支付宝是否审核=sum(case when (m.ChargeType=1 or m.ChargeType=2) and [IFAccountCheck]=1 then 1 else 0 end) 
                  --,支付宝实收合计=sum(case when (m.ChargeType=1) then isnull(m.PaidMoney,0) else 0 end)
                  --,微信实收合计=sum(case when (m.ChargeType=2) then isnull(m.PaidMoney,0) else 0 end)
                  --,银行转账合计=sum(case when (m.ChargeType=3) then isnull(m.PaidMoney,0) else 0 end)
                  ,现金实收合计=sum(case when mpc.ChargeType in (1,2,3) then 0 when (m.ChargeType=0) then isnull(m.PaidMoney,0) else 0 end)
                  ,支付宝实收合计=sum(case when (mpc.ChargeType=1 and m.ChargeOrder=1) then isnull(mpc.PaidMoney,0) else (case when (m.ChargeType=1) then isnull(m.PaidMoney,0) else 0 end) end)
                  ,微信实收合计=sum(case when (mpc.ChargeType=2 and m.ChargeOrder=1) then isnull(mpc.PaidMoney,0)  else (case when (m.ChargeType=2) then isnull(m.PaidMoney,0) else 0 end) end)
                  ,银行转账合计=sum(case when (mpc.ChargeType=3 and m.ChargeOrder=1) then isnull(mpc.PaidMoney,0)  else (case when (m.ChargeType=3) then isnull(m.PaidMoney,0) else 0 end) end)
	              ,医保合计=sum(case when (m.ChargeType in (4,5)) then isnull(m.PaidMoney,0) else 0 end)
	              ,医保退款=sum(case when (m.ChargeType=5) then isnull(m.PaidMoney,0) else 0 end)
	              ,离休合计=sum(case when (m.ChargeType=6) then isnull(m.PaidMoney,0) else 0 end)
                  --,分币误差合计=sum(case when (m.ChargeType=7) then isnull(m.PaidMoney,0) else 0 end)
                  ,分币误差合计=sum(case when mpc.ChargeType in (1,2,3) then 0 else (case when (m.ChargeType=7) then isnull(m.PaidMoney,0) else 0 end) end)
                into #temp
				from M_PatientChargeDetail m 
                left join M_PatientCharge mpc on mpc.TaskCode = m.TaskCode and mpc.PatientOrder = m.PatientOrder ");
            //20210701add--gdg
            if (IFYiBaoTime == 1)
            {
                sb.Append(@"
                   left join #temp3 mpryb on mpc.TaskCode = mpryb.任务编码 and mpc.PatientOrder = mpryb.病历序号
			       where mpryb.交易时间 >=@BeginTime and mpryb.交易时间 <=@EndTime 
                         and m.ChargeDate >=@BeginTime and m.ChargeDate <=@EndTime ");//20210711--gdg
            }
            else
            {
                sb.Append(@"
                  where mpc.Date >=@BeginTime and mpc.Date <=@EndTime ");
            }
            sb.Append(@"
			    group by m.TaskCode,m.PatientOrder

				--select TaskCode
				--,收费类型
				--,是否审核=max(是否审核) 
                --  ,现金实收合计=sum(现金实收合计)
                --  ,支付宝实收合计=sum(支付宝实收合计)
                --  ,微信实收合计=sum(微信实收合计)
                --  ,银行转账合计=sum(银行转账合计)
	            --  ,医保合计=sum(医保合计)
	            --  ,医保退款=sum(医保退款)
	            --  ,离休合计=sum(离休合计)
                --  ,分币误差合计=sum(分币误差合计)
				--  into #temp1
				--from #temp t
			    --group by TaskCode,收费类型

                select 
                TaskCode,PatientOrder
                ,收费类型=left(收费类型,case when len(收费类型)-1>0 then len(收费类型)-1 else 0 end)
                ,是否审核
                ,现金实收合计=isnull(现金实收合计,0)
                  ,支付宝实收合计=isnull(支付宝实收合计,0)
                  ,微信实收合计=isnull(微信实收合计,0)
                  ,银行转账合计=isnull(银行转账合计,0)
	              ,医保合计=isnull(医保合计,0)
	              ,医保退款=isnull(医保退款,0)
	              ,离休合计=isnull(离休合计,0)
                  ,分币误差合计=isnull(分币误差合计,0)
                into #temp5 
                from #temp
				--where charindex(' ',收费类型)>0
                "); //add2021-10-15 plq 医保上线移植

            sb.Append(@"
                  select  ");
            sb.Append("  (select tc.名称 from ").Append(builder.InitialCatalog).Append(".dbo.TStation ts ");
            sb.Append("  left join  ").Append(builder.InitialCatalog).Append(".dbo.TCenter  tc on ts.中心编码 = tc.编码 where ts.[名称] = mpd.Station) as Center ");
            sb.Append(@"
                ,mpd.Station
                ,PatientVersion ");
            sb.Append("  ,").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,3) as Driver");
            sb.Append("  ,").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,4) as Doctor");
            sb.Append("  ,").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,5) as Nurse");
            sb.Append("  ,isnull(").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,4),'')+isnull(").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,5),'') as DoctorAndNurse ");
            sb.Append("  ,").Append(builder.InitialCatalog).Append(".dbo.GetNameWorkStr(mpd.TaskCode,6) as StretcherBearers");

            // 新加为空判断 2016-10-26 yh //20211012 plq 医保上线移植
            sb.Append(@"
                , Date 
                ,tt.生成任务时刻  as  taskDate
				               ");
            //20210701add--gdg
            if (IFYiBaoTime == 1)
            {
                sb.Append(@"
                   ,YiBaoJYTime=mpryb.交易时间 ");
            }
            else
            {
                sb.Append(@"
                  ,YiBaoJYTime='' ");
            }
            sb.Append(@"
                ,InvoiceNumber
                ,ChargeKM
                ,isnull(CarFee,0) as CarFee
                ,isnull(WaitingFee,0)  as WaitingFee
                ,isnull(EmergencyFee,0) as EmergencyFee
                ,isnull(DrugFeeTotal,0) as DrugFeeTotal
                ,isnull(ExamineFeeTotal,0) as ExamineFeeTotal
                ,isnull(ConsumableFeeTotal,0) as ConsumableFeeTotal
                ,isnull(MeasureFeeTotal,0) as MeasureFeeTotal
                ,( isnull(EmergencyFee,0)+ isnull(DrugFeeTotal,0)+ isnull(ExamineFeeTotal,0)+ isnull(ConsumableFeeTotal,0)+ isnull(MeasureFeeTotal,0)) as YLFee
                ,isnull(ReceivableTotal,0) as ReceivableTotal
                ,isnull(PaidMoney,0) as PaidMoney
                ,isnull(PaidCarFee,0) as PaidCarFee
                ,isnull(PaidPRFee,0) as PaidPRFee
                ,ReceivablesPaidInconsistentReasons
                ,(case when tt.是否正常结束 = 1 then '是' else '否' end ) as IFNormalEnd

                --,ChargeType=case when ChargeType=0 then '现金' when ChargeType=1 then '支付宝' when ChargeType=2 then '微信' when ChargeType=3 then '银行转账' end
                ,ChargeType=case when ChargeType=0 then '现金' when ChargeType=1 then '支付宝' when ChargeType=2 then '微信' when ChargeType=3 then '银行转账' when ChargeType=-1 then t1.收费类型 end
                ,IFAccountCheck = case when ((IFAccountCheck=1) or t1.是否审核=1) then '已审核' else '未审核' end 
                ,isnull(t1.现金实收合计,0)  as XianJinTotal
                ,isnull(t1.支付宝实收合计,0)  as ZhiFuBaoTotal
                ,isnull(t1.微信实收合计,0)  as WeiXinTotal
                ,isnull(t1.银行转账合计,0)  as YinHangTotal
                ,isnull(t1.医保合计,0)  as YiBaoTotal
                ,isnull(t1.医保退款,0)  as YiBaoTuiKTotal
                ,isnull(t1.离休合计,0)  as LiXiuTotal
                ,isnull(t1.分币误差合计,0)  as MoLingTotal

                from M_PatientCharge mpc 
                inner join  M_PatientRecord mpd on mpc.TaskCode = mpd.TaskCode and mpc.PatientOrder=mpd.PatientOrder    ");
            sb.Append(" left join  #temp5 t1 on mpc.TaskCode = t1.TaskCode and mpc.PatientOrder= t1.PatientOrder  "); //20211015 plq 医保上线移植
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpc.TaskCode = tt.任务编码 ");

            sb.Append(@"
                left join M_PatientRecordAppend tpra on mpc.TaskCode=tpra.TaskCode and mpc.PatientOrder=tpra.PatientOrder
                --left join   Anchor120V7.dbo.TTaskPersonLink tpl on tt.任务编码 = tpl.任务编码  
                --left join     Anchor120V7.dbo.TPerson tp on tpl.人员编码 = tp.编码

");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on mpd.OutStationCode=ts.编码 ");

            //20210701add--gdg //20211012 plq 医保上线移植
            if (IFYiBaoTime == 1)
            {
                sb.Append(@"
                   left join #temp3 mpryb on mpc.TaskCode = mpryb.任务编码 and mpc.PatientOrder = mpryb.病历序号
			       where mpryb.交易时间 >=@BeginTime and mpryb.交易时间 <=@EndTime ");
            }
            else
            {
                sb.Append(@"
                  where mpc.Date >=@BeginTime and mpc.Date <=@EndTime ");
            }

            //sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'");
            //sb.Append(" where mpc.Date >='" + beginTime + @"' and mpc.Date <='" + endTime + @"'");//20210629gdg改为收费时间--20210701注释

            WhereClauseUtility.AddStringEqual("tt.是否正常结束", IFNormalEnd, sb);
            WhereClauseUtility.AddStringLike("mpd.PatientVersion", eventType, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);

            WhereClauseUtility.AddInSelectQuery("mpd.OutStationCode", stationID, sb);
            WhereClauseUtility.AddStringLike("mpd.DoctorAndNurse", doctorAndNurse, sb);
            WhereClauseUtility.AddStringLike("mpd.Driver", Driver, sb);
            WhereClauseUtility.AddStringLike("mpd.StretcherBearersI", StretcherBearersI, sb);
            WhereClauseUtility.AddStringEqual("mpd.AgentWorkID", agentID, sb);
            WhereClauseUtility.AddStringEqual("mpd.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpd.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpd.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpd.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("tpra.FirstImpression", txtFirstImpression, sb);

            //20211015 plq 医保上线移植
            string ChargeType = "";
            if (chargeType == 0)
            {
                ChargeType = "现金";
                sb.Append("and (mpc.ChargeType like '%" + chargeType + "%' or t1.收费类型 like '%" + ChargeType + "%') ");
                //WhereClauseUtility.AddStringLike("mpc.ChargeType", ChargeType, sb);
            }
            else if (chargeType == 1)
            {
                ChargeType = "支付宝";
                sb.Append("and (mpc.ChargeType = " + chargeType + " or t1.收费类型 like '%" + ChargeType + "%') ");
            }
            else if (chargeType == 2)
            {
                ChargeType = "微信";
                sb.Append("and (mpc.ChargeType = " + chargeType + "  or t1.收费类型 like '%" + ChargeType + "%') ");
            }
            else if (chargeType == 3)
            {
                ChargeType = "转账";
                sb.Append("and (mpc.ChargeType  = " + chargeType + " or t1.收费类型 like '%" + ChargeType + "%') ");
            }
            else if (chargeType == 4)
            {
                ChargeType = "医保";
                sb.Append("and (mpc.ChargeType  = " + chargeType + "  or t1.收费类型 like '%" + ChargeType + "%') ");
            }
            else if (chargeType == 5)
            {
                ChargeType = "医保退款";
                sb.Append("and (mpc.ChargeType  = " + chargeType + " or t1.收费类型 like '%" + ChargeType + "%') ");
            }
            else if (chargeType == 6)
            {
                ChargeType = "离休";
                sb.Append("and (mpc.ChargeType  = " + chargeType + " or t1.收费类型 like '%" + ChargeType + "%') ");//20210620--gdg
            }
            else if (chargeType == 7)
            {
                ChargeType = "分币误差";
                sb.Append("and (mpc.ChargeType  = " + chargeType + " or t1.收费类型 like '%" + ChargeType + "%') ");//20210620--gdg
            }

            if (DriverWC != "")
            {
                sb.Append("and mpd.Driver in (select tp.姓名 from ").Append(builder.InitialCatalog).Append(".dbo.TPerson tp where tp.工号 = '" + DriverWC + "') ");
            }
            if (DoctorWC != "")
            {
                sb.Append("and mpd.DoctorAndNurse in (select tp.姓名 from ").Append(builder.InitialCatalog).Append(".dbo.TPerson tp where tp.工号 = '" + DoctorWC + "') ");
            }
            if (StretcherBearersWC != "")
            {
                sb.Append("and mpd.StretcherBearersI in (select tp.姓名 from ").Append(builder.InitialCatalog).Append(".dbo.TPerson tp where tp.工号 = '" + StretcherBearersWC + "') ");
            }

            if (IFAccountCheck != "") //2020-05-14 zch //20211015 plq 医保上线移植
            {
                if (IFAccountCheck == "1")
                    //WhereClauseUtility.AddStringEqual("mpc.IFAccountCheck", "1", sb);//20210625-gdg注释
                    sb.Append("and ((mpc.IFAccountCheck=1) or t1.是否审核=1)  ");//20210625add-gdg
                else
                    sb.Append("and ((mpc.IFAccountCheck IS NULL OR mpc.IFAccountCheck=0)) ");
            }

            sb.Append(@"   order by InvoiceNumber desc ");

            if (IFYiBaoTime == 1) //20211015 plq 医保上线移植
            {
                sb.Append(@"  drop table #temp,#temp3,#temp5  ");//20210706,#temp1
            }
            else
            {
                sb.Append(@"  drop table #temp,#temp5  ");//20210706,#temp1
            }
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];

        }

        #endregion

        #region  人员操作状态流水表
        /// <summary>
        /// 人员操作状态流水表
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_RYCZZT(DateTime beginTime, DateTime endTime)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select 状态=Description,操作时间=OperationTime,操作人=OperationPerson
                      from TStateLog                      
                      where OperationTime>='" + beginTime + "' and OperationTime<='" + endTime + "' ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 油卡基础信息流水表
        public DataTable Get_LS_YKJCXX(string centerID, string stationID, string cardCode, string driverWorkID,
                                       string driverName, string isActive, string isFanBan)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   分中心=tc.名称,分站=ts.名称,油卡负责人工号=oci.DriverWorkID,油卡负责人姓名=oci.DriverName,卡号=oci.CardCode,
                                 卡内金额=Convert(decimal(18,2),oci.CardAmount),填写日期=oci.FillTime,填写人=oci.FillPerson,
                                 备注=oci.Remark,是否有效=case when oci.IsActive=1 then '是' when oci.IsActive=0 then '否' end,
                                 是否翻班=case when oci.IsFanBan=1 then '是' when oci.IsFanBan=0 then '否'  end            
                        from C_OilCardInfo oci 
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on oci.StationID=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on oci.CenterID=tc.编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddStringLike("oci.CardCode", cardCode, sb);
            WhereClauseUtility.AddStringEqual("oci.CenterID", centerID, sb);
            WhereClauseUtility.AddStringEqual("oci.StationID", stationID, sb);
            WhereClauseUtility.AddStringLike("oci.DriverWorkID", driverWorkID, sb);
            WhereClauseUtility.AddStringLike("oci.DriverName", driverName, sb);
            WhereClauseUtility.AddStringEqual("oci.IsActive", isActive, sb);
            WhereClauseUtility.AddStringEqual("oci.IsFanBan", isFanBan, sb);
            sb.Append(" order by oci.FillTime desc ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region 油卡充值流水表
        public DataTable Get_LS_YKCZ(DateTime beginTime, DateTime endTime, string centerID, string stationID, string cardCode
                                     , E_StatisticsPermisson em, string selfCenterID, string selfStationID, string selfWorkCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   分中心=tc.名称,分站=ts.名称,司机工号=ocr.DriverWorkID,司机姓名=ocr.DriverName,卡号=ocr.CardCode,
                                 卡内余额=Convert(decimal(18,2),ocr.Remaining),充值金额=Convert(decimal(18,2),ocr.RechargeAmount),
                                 卡内金额=Convert(decimal(18,2),ocr.CardAmount),充值日期=ocr.RechargeTime,充值发票编号=ocr.FPCode,
                                 备注=ocr.Remark                 
                        from C_OilCardRecharge ocr 
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ocr.StationID=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on ocr.CenterID=tc.编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("ocr.RechargeTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("ocr.RechargeTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("ocr.CardCode", cardCode, sb);
            if (em == E_StatisticsPermisson.None)
                return null;

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                    WhereClauseUtility.AddStringEqual("ocr.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.StationID", stationID, sb);
                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    WhereClauseUtility.AddStringEqual("ocr.CenterID", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.StationID", stationID, sb);
                }
                else if (em == E_StatisticsPermisson.STATION)
                {
                    WhereClauseUtility.AddStringEqual("ocr.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.StationID", selfStationID, sb);
                }
                else if (em == E_StatisticsPermisson.SELF)
                {
                    WhereClauseUtility.AddStringEqual("ocr.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.StationID", stationID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.DriverWorkID", selfWorkCode, sb);
                }
                sb.Append(" order by 充值日期 desc ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
        }
        #endregion

        #region 油卡加油流水表
        public DataTable Get_LS_YKJY(DateTime beginTime, DateTime endTime, string centerID, string stationID, string actualCode,
                                     string ambulanceNumber, string cardCode, string shift, string oilType, string refuelPerson
                                     , E_StatisticsPermisson em, string selfCenterID, string selfStationID, string selfWorkCode, string selfName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   分中心=tc.名称,分站=ts.名称,司机工号=ocr.DriverWorkID,司机姓名=ocr.DriverName,卡号=ocr.CardCode,
                                 班次=ocr.Shift,车牌号码=ocr.ActualCode,车辆编号=ocr.AmbulanceNumber,加油油号=ocr.OilType,
                                 加油量=Convert(decimal(18,2),ocr.OilMass),加油金额=Convert(decimal(18,2),ocr.RefuelMoney),
                                 加油日期=ocr.RefuelTime,上次加油路码=Convert(decimal(18,2),ocr.LastGasPathCode),备注=ocr.Remark,        
                                 本次加油路码=Convert(decimal(18,2),ocr.GasPathCode),行驶公里=Convert(decimal(18,2),ocr.DrivingKM)
                                 ,加油人=ocr.RefuelPerson,凭证编号=ocr.ProofNumber,卡内余额=ocr.bakup2                                     
                        from C_OilCardRefuel ocr 
                        left join C_Ambulance ca on ca.AmbulanceCode = ocr.AmbulanceCode
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ocr.StationID=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on ocr.CenterID=tc.编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("ocr.RefuelTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("ocr.RefuelTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("ocr.CardCode", cardCode, sb);
            WhereClauseUtility.AddStringEqual("ocr.Shift", shift, sb);
            WhereClauseUtility.AddStringEqual("ocr.OilType", oilType, sb);
            WhereClauseUtility.AddStringLike("ocr.RefuelPerson", refuelPerson, sb);
            if (em == E_StatisticsPermisson.None)
                return null;

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", stationID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", stationID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.STATION)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", selfStationID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.SELF)
                {
                    WhereClauseUtility.AddStringEqual("ca.CenterCode", centerID, sb);
                    WhereClauseUtility.AddStringEqual("ca.StationCode", stationID, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", ambulanceNumber, sb);
                    WhereClauseUtility.AddStringEqual("ocr.RefuelPerson", selfName, sb);
                }
                sb.Append(" order by 加油日期 desc ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
        }
        #endregion

        #region 整修保养流水表
        public DataTable Get_LS_ZXBY(DateTime beginTime, DateTime endTime, string centerID, string stationID, string actualCode, string ambulanceNumber
                                      , string sendConfirmedPerson, string repairPerson, string inspector, string acceptor, string repairType
                                      , E_StatisticsPermisson em, string selfCenterID, string selfStationID, string selfWorkCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   分中心=tc.名称,分站=ts.名称,车牌号码=rm.ActualCode,车辆编号=rm.AmbulanceNumber,修理类别=rm.RepairType,
                                 是否更改路码=case when rm.IsChangeRoadCode=1 then '是' else '否' end,进厂里程表数=rm.InMileage,
                                 出厂里程表数=rm.OutMileage,进厂油量=rm.InOilMass,出厂油量=rm.OutOilMass,
                                 有无备胎=case when rm.IsSpareWheel=1 then '有' else '无' end,
                                 有无行驶证=case when rm.IsDrivingLicense=1 then '有' else '无' end,送保日期=rm.SendConfirmedTime,
                                 竣工日期=rm.CompletionTime,整修项目=rm.RepairContent,送保人=rm.SendConfirmedPerson,承修人=rm.RepairPerson,
                                 车间检验员=rm.Inspector,分站管理科验收人=rm.Acceptor,备注=rm.Remark                                                                 
                        from C_RepairMaintain  rm
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on rm.StationID=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on rm.CenterID=tc.编码 ");
            //sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TPerson tp on rm.StationID=tp.分站编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("rm.SendConfirmedTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("rm.SendConfirmedTime", endTime, sb);
            WhereClauseUtility.AddStringLike("rm.SendConfirmedPerson", sendConfirmedPerson, sb);
            WhereClauseUtility.AddStringLike("rm.RepairPerson", repairPerson, sb);
            WhereClauseUtility.AddStringLike("rm.Inspector", inspector, sb);
            WhereClauseUtility.AddStringLike("rm.Acceptor", acceptor, sb);
            WhereClauseUtility.AddStringEqual("rm.RepairType", repairType, sb);
            if (em == E_StatisticsPermisson.None)
                return null;

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                    WhereClauseUtility.AddStringEqual("rm.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("rm.StationID", stationID, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    sb.Append(" and 1=2");
                    WhereClauseUtility.AddStringEqual("rm.CenterID", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("rm.StationID", stationID, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.STATION)
                {
                    sb.Append(" and 1=2");
                    WhereClauseUtility.AddStringEqual("rm.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("rm.StationID", selfStationID, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.SELF)
                {
                    sb.Append(" and 1=2");
                    WhereClauseUtility.AddStringEqual("rm.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("rm.StationID", selfStationID, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("rm.AmbulanceCode", ambulanceNumber, sb);
                    //WhereClauseUtility.AddStringEqual("tp.工号", selfWorkCode, sb);
                }
                sb.Append(" order by 送保日期 desc ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
        }
        #endregion

        #region 违章管理流水表
        public DataTable Get_LS_WZGL(DateTime beginTime, DateTime endTime, string centerID, string stationID, string actualCode,
                                      string ambulanceNumber, string place, string driverName, string driverWorkID
                                      , E_StatisticsPermisson em, string selfCenterID, string selfStationID, string selfWorkCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   分中心=tc.名称,分站=ts.名称,车牌号码=vio.ActualCode,车辆编号=vio.AmbulanceNumber,违章地点=vio.ViolationPlace,
                                 违章内容=vio.ViolationContent,违章日期=convert(varchar(10),vio.ViolationTime,120),责任司机工号=vio.DriverWorkID,
                                 责任司机=vio.DriverName,违章处理结果=vio.DisposeResult,处理日期=convert(varchar(10),vio.DisposeTime,120),备注=vio.Remark                                                                 
                        from C_Violation  vio
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on vio.StationID=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on vio.CenterID=tc.编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("vio.ViolationTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("vio.ViolationTime", endTime, sb);
            WhereClauseUtility.AddStringLike("vio.ViolationPlace", place, sb);
            WhereClauseUtility.AddStringEqual("vio.DriverName", driverName, sb);
            WhereClauseUtility.AddStringEqual("vio.DriverWorkID", driverWorkID, sb);
            if (em == E_StatisticsPermisson.None)
                return null;

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                    WhereClauseUtility.AddStringEqual("vio.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("vio.StationID", stationID, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    WhereClauseUtility.AddStringEqual("vio.CenterID", selfCenterID, sb);
                    WhereClauseUtility.AddStringEqual("vio.StationID", stationID, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.STATION)
                {
                    sb.Append(" and 1=2");
                    WhereClauseUtility.AddStringEqual("vio.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("vio.StationID", selfStationID, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", ambulanceNumber, sb);
                }
                else if (em == E_StatisticsPermisson.SELF)
                {
                    sb.Append(" and 1=2");
                    WhereClauseUtility.AddStringEqual("vio.CenterID", centerID, sb);
                    WhereClauseUtility.AddStringEqual("vio.StationID", selfStationID, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", actualCode, sb);
                    WhereClauseUtility.AddStringEqual("vio.AmbulanceCode", ambulanceNumber, sb);
                    WhereClauseUtility.AddStringEqual("vio.DriverWorkID", selfWorkCode, sb);
                }
                sb.Append(" order by 违章日期 desc ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
                return ds.Tables[0];
            }
        }
        #endregion

        #region 入库单流水表
        public DataTable Get_LS_EntryList(DateTime beginTime, DateTime endTime, string instr, string entryStorage, string entryListType, string entryListCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select 入库日期=EntryDate,入库单号=EntryCode,入库单类型=td.Name,入库仓库=st.Name,经办人=us.Name,经办时间=OperationTime,备注=en.Remark
                        from I_Entry en
                        left join I_Storage st on st.StorageID=en.EntryStorageID
                        left join TDictionary td on td.ID=en.EntryType
                        left join P_User us on us.ID=en.OperatorCode
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("en.EntryDate", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("en.EntryDate", endTime, sb);
            WhereClauseUtility.AddInSelectQuery("en.EntryStorageID", instr, sb);
            WhereClauseUtility.AddStringEqual("en.EntryType", entryListType, sb);
            WhereClauseUtility.AddStringEqual("en.EntryStorageID", entryStorage, sb);
            WhereClauseUtility.AddStringLike("en.EntryCode", entryListCode, sb);
            sb.Append(" order by EntryDate desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 新入库单流水表 2018-01-22 zzm
        public DataTable Get_LS_XEntryList(DateTime beginTime, DateTime endTime, string instr, string entryStorage, string entryListType, string entryListCode
            , string classification, string material, string vendor)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  供应商=m.Vendor
                                ,生产厂家=m.Manufacturer
                                ,物品编码=MCode
                                ,物品名称=m.Name
                                ,规格=m.Specification
                                ,单位=td.Name
                                ,入库数量=en.EntryCounts
                                ,单价=m.UnitPrice
                                ,金额小计=en.TotalPrice
                                ,备注=en.Remark
                                ,入库单号=en.EntryDetailCode
                                ,入库方向=st.Name
                                ,入库时间=CONVERT(varchar(100), en.EntryDate, 20)
                                ,有效期=CONVERT(varchar(100), en.ValidityDate, 20)
                                ,入库批号=en.RealBatchNo
                                from I_EntryDetail en
								left join I_Entry e on e.EntryCode=en.EntryCode
                                left join I_Material m on m.ID=en.MaterialID
                                left join TDictionary td on td.ID=m.Unit
                                left join I_Storage st on st.StorageID=e.EntryStorageID
                                left join P_User us on us.ID=en.OperatorCode
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddStringEqual("m.MTypeID", classification, sb);
            WhereClauseUtility.AddStringEqual("en.MaterialID", material, sb);
            WhereClauseUtility.AddDateTimeGreaterThan("en.EntryDate", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("en.EntryDate", endTime, sb);
            WhereClauseUtility.AddInSelectQuery("e.EntryStorageID", instr, sb);
            WhereClauseUtility.AddStringEqual("en.EntryType", entryListType, sb);
            WhereClauseUtility.AddStringEqual("e.EntryStorageID", entryStorage, sb);
            WhereClauseUtility.AddStringLike("en.EntryCode", entryListCode, sb);
            WhereClauseUtility.AddStringLike("m.Vendor", vendor, sb);
            sb.Append(" order by en.EntryDate desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

       




        #region 出库单流水表
        public DataTable Get_LS_DeliveryList(DateTime beginTime, DateTime endTime, string sourceStorage, string targetStorage,
                                             string instr, string classification, string material, string deliveryListCode,
                                             string deliveryType, string receiver, string receiverAmbulance, string operater)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  出库日期=dd.DeliveryTime
                        ,批次号=dd.BatchNo
                        ,物资名称=ma.Name
                        ,出库数量=dd.DeliveryCounts
                        ,单位=td2.Name
                        ,规格=ma.Specification
                        ,源仓库=st1.Name
                        ,目标仓库=st2.Name
                        ,经办人=us1.Name
						,领取人=us2.Name
						,车牌号码=ca.PlateNumber
						,出库单类型=td1.Name,备注=dd.Remark
                        from I_DeliveryDetail dd
                        left join I_Material ma on ma.ID=dd.MaterialID
                        left join I_Delivery dl on dl.DeliveryCode=dd.DeliveryCode
                        left join I_Storage st1 on st1.StorageID=dd.EntryStorageCode
                        left join I_Storage st2 on st2.StorageID=dd.TargetStorageCode
                        left join P_User us1 on us1.ID=dd.OperatorCode
						left join P_User us2 on us2.ID=dl.ConsigneeID
                        left join TDictionary td1 on td1.ID=dl.DeliveryType
                        left join TDictionary td2 on td2.ID=ma.Unit
					    left join C_Ambulance ca on ca.AmbulanceCode=dl.AmbulanceCode
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("dd.DeliveryTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("dd.DeliveryTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("dd.EntryStorageCode", sourceStorage, sb);

            //if (targetStorage != "-1")
            //{
            //    WhereClauseUtility.AddStringEqual("dd.TargetStorageCode", targetStorage, sb);
            //}
            //else
            //{
            //    sb.Append("and dd.TargetStorageCode= -1");
            //}
            //新加选择东南西北中大区以及东南西北中医生大区时查询其所属子类的所有数据   2016-07-05  yh
            //if (targetStorage != "5" && targetStorage != "6" && targetStorage != "7" && targetStorage != "9" && targetStorage != "10"
            //    && targetStorage != "57" && targetStorage != "65" && targetStorage != "86" && targetStorage != "59" && targetStorage != "67")
            //{
            //    if (targetStorage == "" || targetStorage == "--请选择--")
            //    { sb.Append(" and 1=1 "); }
            //    else
            //    { sb.Append(" and dd.TargetStorageCode='" + targetStorage + "'"); }
            //}

            ////目标仓库选择东区，汇总东区下的分站子仓库
            //if (targetStorage == "5")
            //{
            //    sb.Append(" and (st2.ParentStorageID=5 or st2.ParentStorageID=57) ");
            //}
            ////目标仓库选择东区医生个人仓库，汇总所有东区医生个人仓库
            //if (targetStorage == "57")
            //{
            //    sb.Append(" and st2.ParentStorageID=57 ");
            //}
            ////目标仓库选择西区，汇总西区下的分站子仓库
            //if (targetStorage == "6")
            //{
            //    sb.Append(" and (st2.ParentStorageID=6 or st2.ParentStorageID=86 )");
            //}
            ////目标仓库选择西区医生个人仓库，汇总所有西区医生个人仓库
            //if (targetStorage == "86")
            //{
            //    sb.Append(" and st2.ParentStorageID=86 ");
            //}
            ////目标仓库选择南区，汇总南区下的分站子仓库
            //if (targetStorage == "7")
            //{
            //    sb.Append(" and (st2.ParentStorageID=7 or st2.ParentStorageID=65) ");
            //}
            ////目标仓库选择南区医生个人仓库，汇总所有南区医生个人仓库
            //if (targetStorage == "65")
            //{
            //    sb.Append(" and st2.ParentStorageID=65 ");
            //}
            ////目标仓库选择北区，汇总北区下的分站子仓库
            //if (targetStorage == "9")
            //{
            //    sb.Append(" and (st2.ParentStorageID=9 or st2.ParentStorageID=59) ");
            //}
            ////目标仓库选择北区医生个人仓库，汇总所有北区医生个人仓库
            //if (targetStorage == "59")
            //{
            //    sb.Append(" and st2.ParentStorageID=59 ");
            //}
            ////目标仓库选择中区，汇总中区下的分站子仓库
            //if (targetStorage == "10")
            //{
            //    sb.Append(" and (st2.ParentStorageID=10 or st2.ParentStorageID=67) ");
            //}
            ////目标仓库选择中区医生个人仓库，汇总所有中区医生个人仓库
            //if (targetStorage == "67")
            //{
            //    sb.Append(" and st2.ParentStorageID=67 ");
            //}
            WhereClauseUtility.AddInSelectQuery("dd.EntryStorageCode", instr, sb);
            WhereClauseUtility.AddStringEqual("ma.MTypeID", classification, sb);
            WhereClauseUtility.AddStringEqual("dd.MaterialID", material, sb);
            WhereClauseUtility.AddStringLike("dd.DeliveryCode", deliveryListCode, sb);
            WhereClauseUtility.AddStringEqual("dl.DeliveryType", deliveryType, sb);
            WhereClauseUtility.AddStringEqual("us2.Name", receiver, sb);
            WhereClauseUtility.AddStringEqual("dl.AmbulanceCode", receiverAmbulance, sb);
            WhereClauseUtility.AddStringLike("us1.Name", operater, sb);//新增经办人查询条件 2016-07-01 youhao
            sb.Append(" order by dd.DeliveryTime desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 新出库单流水表  2018-01-22 zzm
        public DataTable Get_LS_XDeliveryList(DateTime beginTime, DateTime endTime, string sourceStorage, string targetStorage,
                                             string instr, string classification, string material, string deliveryListCode,
                                             string deliveryType, string receiver, string receiverAmbulance, string operater)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  物品编码=MCode
                                ,物品名称=ma.Name
                                ,规格=ma.Specification
                                ,单位=td2.Name
                                ,出库数量=dd.DeliveryCounts
                                ,单价=ma.UnitPrice
                                ,备注=dd.Remark
                                --,入库数量=en.EntryCounts
								--,入库总金额=en.TotalPrice
								,出库单号=dd.DeliveryCode
								,出库方向=st2.Name
								,出库日期=CONVERT(varchar(100), dd.DeliveryTime, 20)
                                ,有效期=CONVERT(varchar(100), isu.ValidityDate, 20)
                                ,出库批号=dd.RealBatchNo,生产厂家=ma.Manufacturer
                        from I_DeliveryDetail dd
                        left join I_Material ma on ma.ID=dd.MaterialID
                        --left join I_EntryDetail en on en.EntryDetailCode=dd.DeliveryDetailCode
                        left join I_Delivery dl on dl.DeliveryCode=dd.DeliveryCode
                        left join I_Storage st1 on st1.StorageID=dd.EntryStorageCode
                        left join I_Storage st2 on st2.StorageID=dd.TargetStorageCode
                        left join P_User us1 on us1.ID=dd.OperatorCode
						left join P_User us2 on us2.ID=dl.ConsigneeID
                        left join TDictionary td1 on td1.ID=dl.DeliveryType
                        left join TDictionary td2 on td2.ID=ma.Unit
					    left join C_Ambulance ca on ca.AmbulanceCode=dl.AmbulanceCode
                        left join I_Surplus isu on isu.RealBatchNo=dd.RealBatchNo and isu.StorageCode=dd.TargetStorageCode
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("dd.DeliveryTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("dd.DeliveryTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("dd.EntryStorageCode", sourceStorage, sb);

            ////if (targetStorage != "-1")
            ////{
            ////    WhereClauseUtility.AddStringEqual("dd.TargetStorageCode", targetStorage, sb);
            ////}
            ////else
            ////{
            ////    sb.Append("and dd.TargetStorageCode= -1");
            ////}
            ////新加选择东南西北中大区以及东南西北中医生大区时查询其所属子类的所有数据   2016-07-05  yh
            //if (targetStorage != "5" && targetStorage != "6" && targetStorage != "7" && targetStorage != "9" && targetStorage != "10"
            //    && targetStorage != "57" && targetStorage != "65" && targetStorage != "86" && targetStorage != "59" && targetStorage != "67")
            //{
            //    if (targetStorage == "" || targetStorage == "--请选择--")
            //    { sb.Append(" and 1=1 "); }
            //    else
            //    { sb.Append(" and dd.TargetStorageCode='" + targetStorage + "'"); }
            //}

            ////目标仓库选择东区，汇总东区下的分站子仓库
            //if (targetStorage == "5")
            //{
            //    sb.Append(" and (st2.ParentStorageID=5 or st2.ParentStorageID=57) ");
            //}
            ////目标仓库选择东区医生个人仓库，汇总所有东区医生个人仓库
            //if (targetStorage == "57")
            //{
            //    sb.Append(" and st2.ParentStorageID=57 ");
            //}
            ////目标仓库选择西区，汇总西区下的分站子仓库
            //if (targetStorage == "6")
            //{
            //    sb.Append(" and (st2.ParentStorageID=6 or st2.ParentStorageID=86 )");
            //}
            ////目标仓库选择西区医生个人仓库，汇总所有西区医生个人仓库
            //if (targetStorage == "86")
            //{
            //    sb.Append(" and st2.ParentStorageID=86 ");
            //}
            ////目标仓库选择南区，汇总南区下的分站子仓库
            //if (targetStorage == "7")
            //{
            //    sb.Append(" and (st2.ParentStorageID=7 or st2.ParentStorageID=65) ");
            //}
            ////目标仓库选择南区医生个人仓库，汇总所有南区医生个人仓库
            //if (targetStorage == "65")
            //{
            //    sb.Append(" and st2.ParentStorageID=65 ");
            //}
            ////目标仓库选择北区，汇总北区下的分站子仓库
            //if (targetStorage == "9")
            //{
            //    sb.Append(" and (st2.ParentStorageID=9 or st2.ParentStorageID=59) ");
            //}
            ////目标仓库选择北区医生个人仓库，汇总所有北区医生个人仓库
            //if (targetStorage == "59")
            //{
            //    sb.Append(" and st2.ParentStorageID=59 ");
            //}
            ////目标仓库选择中区，汇总中区下的分站子仓库
            //if (targetStorage == "10")
            //{
            //    sb.Append(" and (st2.ParentStorageID=10 or st2.ParentStorageID=67) ");
            //}
            ////目标仓库选择中区医生个人仓库，汇总所有中区医生个人仓库
            //if (targetStorage == "67")
            //{
            //    sb.Append(" and st2.ParentStorageID=67 ");
            //}
            WhereClauseUtility.AddInSelectQuery("dd.EntryStorageCode", instr, sb);
            WhereClauseUtility.AddStringEqual("ma.MTypeID", classification, sb);
            WhereClauseUtility.AddStringEqual("dd.MaterialID", material, sb);
            WhereClauseUtility.AddStringLike("dd.DeliveryCode", deliveryListCode, sb);
            WhereClauseUtility.AddStringEqual("dl.DeliveryType", deliveryType, sb);
            WhereClauseUtility.AddStringEqual("us2.Name", receiver, sb);
            WhereClauseUtility.AddStringEqual("dl.AmbulanceCode", receiverAmbulance, sb);
            WhereClauseUtility.AddStringLike("us1.Name", operater, sb);//新增经办人查询条件 2016-07-01 youhao
            sb.Append(" order by dd.DeliveryTime desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 车辆整修保养打印报表
        public DataTable Get_TJ_RepairPrint1(string id)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  分站=ts.名称,车型=td.Name,车牌号码=crm.ActualCode,车辆编号=crm.AmbulanceNumber,修理类别=crm.RepairType,
                        进厂里程表数=crm.InMileage,出厂里程表数=crm.OutMileage,进厂油量=crm.InOilMass,出厂油量=crm.OutOilMass,
		                备胎有无=case when crm.IsSpareWheel=1 then '有' else '无' end,
		                行驶证有无=case when crm.IsDrivingLicense=1 then '有' else '无' end,
		                送保日期=crm.SendConfirmedTime,竣工日期=crm.CompletionTime,整修保养项目=crm.RepairContent,
		                送保人=crm.SendConfirmedPerson,承修人=crm.RepairPerson,车间检验员=Inspector,分站管理科验收人=Acceptor,
		                备注=crm.Remark

		                from C_RepairMaintain crm 
		                left join  C_Ambulance ca on ca.AmbulanceCode=crm.AmbulanceCode 
                        left join  TDictionary td on td.ID=ca.Brand ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ts.编码=crm.StationID ");
            sb.Append(" where crm.ID='" + id + "' ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        public DataTable Get_TJ_RepairPrint2(string ambulanceCode, DateTime startTime, DateTime endTime)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"SELECT  零件名称=im.Name,数量=idd.DeliveryCounts,价格=im.RealPrice
                        FROM  I_DeliveryDetail idd
                        left join I_Delivery id on id.DeliveryCode=idd.DeliveryCode
                        left join I_Material im on im.ID=idd.MaterialID
		                where  id.DeliveryTime>'" + startTime + "' and  id.DeliveryTime<'" + endTime + "' and id.AmbulanceCode='" + ambulanceCode + @"'  
                        ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion


        #region 物资结余流水表 2016-01-15
        /// <summary>
        /// ck仓库 fl分类 wz物资
        /// </summary>
        /// <param name="str"></param>
        /// <param name="ck"></param>
        /// <param name="fl"></param>
        /// <param name="wz"></param>
        /// <returns></returns>
        //        public DataTable Get_LS_WZXX(string str, string ck, string fl, string wz)
        //        {
        //            StringBuilder sb = new StringBuilder();
        //            sb.Append(@"
        //                     select m.Name as 物资名称 , m.Mcode as 物资代码,s.BatchNo as 批次号 ,m.Specification as 规格 ,d.Name as 单位 ,有效期=case when year(s.[ValidityDate])= '9999' then '无有效期'else convert(varchar,s.[ValidityDate],20) end ,s.EntryCounts as 总库存 , s.Surplus as 当前结余 ,st.Name  as 仓库,m.Manufacturer as 生产厂家 ,m.Vendor  as 供应商
        //                     from [dbo].[I_Surplus] as s 
        //                     inner join [dbo].[I_Storage] st on s.StorageCode=st.StorageID 
        //                     inner join [dbo].[I_Material] m on m.ID =s.MaterialID 
        //                     inner join [dbo].[TDictionary]  d on d.ID =m.Unit
        //                     where 1=1 and s.[ValidityDate]>GETDATE () and s.Surplus>0 and s.StorageCode!=-1  
        //                     ");
        //            WhereClauseUtility.AddInSelectQuery("st.StorageID", str, sb);
        //            WhereClauseUtility.AddStringEqual("st.StorageID", ck, sb);
        //            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
        //            WhereClauseUtility.AddStringEqual("s.MaterialID", wz, sb);
        //            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
        //            return ds.Tables[0];
        //        }
        public DataTable Get_LS_WZXX(string str, string ck, string fl, string wz, string time)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@" select 物资代码=MaterialID,最大时间=max(OperatorDateTime) 
					     into #temp1
					     from I_InventoryRecord  ir
                         left join I_Material m on m.ID=ir.MaterialID
				         where OperatorDateTime<'" + time + @"' ");
            WhereClauseUtility.AddStringEqual("StorageCode", ck, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringEqual("ir.MaterialID", wz, sb);
            sb.Append(@" group by MaterialID 

					     select 物资代码=MaterialID,最小时间=min(OperatorDateTime) 
					     into #temp2
					     from I_InventoryRecord  ir
                         left join I_Material m on m.ID=ir.MaterialID
				         where OperatorDateTime>'" + time + @"' ");
            WhereClauseUtility.AddStringEqual("StorageCode", ck, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringEqual("ir.MaterialID", wz, sb);
            sb.Append(@" group by MaterialID

                           select distinct m.Name as 物资名称 ,Convert(decimal(18,2),m.RealPrice) as '单价',(m.RealPrice * iir.Surplus) as '金额', m.Mcode as 物资代码,s.RealBatchNo as 批次号 ,m.Specification as 规格 ,d.Name as 单位
					      ,有效期=case when year(s.[ValidityDate])= '9999' then '无有效期'else convert(varchar,s.[ValidityDate],20) end 
					      ,s.EntryCounts as 总库存 , iir.Surplus as 当前结余 ,st.Name  as 仓库,m.Manufacturer as 生产厂家 ,m.Vendor  as 供应商
                         from #temp1 t1
					     left join dbo.I_InventoryRecord iir on iir.MaterialID=t1.物资代码 and t1.最大时间=iir.OperatorDateTime
					     left join [dbo].[I_Surplus] as s  on s.MaterialID=iir.MaterialID and s.BatchNo=iir.BatchNo
                         left join [dbo].[I_Storage] st on s.StorageCode=st.StorageID 
                         left join [dbo].[I_Material] m on m.ID =s.MaterialID 
                         left join [dbo].[TDictionary]  d on d.ID =m.Unit
					     where 1=1 and s.[ValidityDate]>GETDATE () and s.Surplus>0 and s.StorageCode!=-1 ");
            WhereClauseUtility.AddInSelectQuery("iir.StorageCode", str, sb);
            WhereClauseUtility.AddInSelectQuery("st.StorageID", str, sb);
            WhereClauseUtility.AddStringEqual("st.StorageID", ck, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringEqual("iir.MaterialID", wz, sb);

            sb.Append(@" union all 

					     select distinct m.Name as 物资名称 , Convert(decimal(18,2),m.RealPrice) as '单价',(m.RealPrice * iir.Surplus) as '金额',m.Mcode as 物资代码,s.RealBatchNo as 批次号 ,m.Specification as 规格 ,d.Name as 单位
					      ,有效期=case when year(s.[ValidityDate])= '9999' then '无有效期'else convert(varchar,s.[ValidityDate],20) end 
					      ,s.EntryCounts as 总库存 , iir.OriginalSurplus as 当前结余 ,st.Name  as 仓库,m.Manufacturer as 生产厂家 ,m.Vendor  as 供应商				 
				         from #temp2 t2
					     left join dbo.I_InventoryRecord iir on iir.MaterialID=t2.物资代码 and t2.最小时间=iir.OperatorDateTime
					     left join [dbo].[I_Surplus] as s  on s.MaterialID=iir.MaterialID and s.BatchNo=iir.BatchNo
                         left join [dbo].[I_Storage] st on s.StorageCode=st.StorageID 
                         left join [dbo].[I_Material] m on m.ID =s.MaterialID 
                         left join [dbo].[TDictionary]  d on d.ID =m.Unit
					     where 1=1 and s.[ValidityDate]>GETDATE () and s.StorageCode!=-1 
					     and iir.MaterialID not in(select MaterialID from I_InventoryRecord where OperatorDateTime<'" + time + @"') ");
            WhereClauseUtility.AddInSelectQuery("iir.StorageCode", str, sb);
            WhereClauseUtility.AddInSelectQuery("st.StorageID", str, sb);
            WhereClauseUtility.AddStringEqual("st.StorageID", ck, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringEqual("iir.MaterialID", wz, sb);

            sb.Append(@" union all 

					      select distinct m.Name as 物资名称 ,Convert(decimal(18,2),m.RealPrice) as '单价',(m.RealPrice * iir.Surplus) as '金额', m.Mcode as 物资代码,s.RealBatchNo as 批次号 ,m.Specification as 规格 ,d.Name as 单位
					      ,有效期=case when year(s.[ValidityDate])= '9999' then '无有效期'else convert(varchar,s.[ValidityDate],20) end 
					      ,s.EntryCounts as 总库存 , iir.Surplus as 当前结余 ,st.Name  as 仓库,m.Manufacturer as 生产厂家 ,m.Vendor  as 供应商
					     from [dbo].[I_Surplus] as s 
					     left join dbo.I_InventoryRecord iir on iir.MaterialID=s.MaterialID and iir.batchNO=s.batchNO
					     left join [dbo].[I_Storage] st on s.StorageCode=st.StorageID 
                         left join [dbo].[I_Material] m on m.ID =s.MaterialID 
                         left join [dbo].[TDictionary]  d on d.ID =m.Unit
					      where 1=1 and s.[ValidityDate]>GETDATE ()  and s.StorageCode!=-1                    
					      and s.MaterialID not in(select MaterialID from I_InventoryRecord ) ");
            WhereClauseUtility.AddInSelectQuery("st.StorageID", str, sb);
            WhereClauseUtility.AddStringEqual("st.StorageID", ck, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringEqual("iir.MaterialID", wz, sb);
            sb.Append(" drop table #temp1,#temp2 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 物资基础信息流水表 2016-01-18
        /// <summary>
        /// sccj生产厂家 gys供应商 enable有效 fl分类 wz物资
        /// </summary>
        /// <param name="sccj"></param>
        /// <param name="gys"></param>
        /// <param name="enable"></param>
        /// <param name="fl"></param>
        /// <param name="wz"></param>
        /// <returns></returns>
        public DataTable Get_LS_WZJCXX(string sccj, string gys, string enable, string fl, string wz)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      select s.name as 物资分类 ,m.Name as 物资名称,m.MCode as 物资代码
                      ,d.Name as 度量单位,m.[Specification] as 规格 ,
                      m.Manufacturer as 生产厂家,m.Vendor  as 供应商,m.AlarmCounts as 警示基数,m.RealPrice as 销售价格,是否有效=case when m.IsActive =0 then '无效' else '有效' end ,项目编码=case when m.ProjectCode=null then '' end,m.Remark as 备注
                      from [I_Material] m
                      left join [dbo].[TDictionary]  d on d.ID =m.Unit 
                      left join [dbo].[TDictionary]  s  on s.ID =m.[MTypeID]
                      where m.MTypeID!='nulltype'
                     ");
            WhereClauseUtility.AddStringEqual("m.Manufacturer", sccj, sb);
            WhereClauseUtility.AddStringEqual("m.Vendor", gys, sb);
            WhereClauseUtility.AddStringEqual("m.IsActive", enable, sb);
            WhereClauseUtility.AddStringEqual("m.MTypeID", fl, sb);
            WhereClauseUtility.AddStringLike("m.ID", wz, sb);
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 重打发票流水表 2016-01-19
        /// <summary>
        /// 发票号码tbf 流水号tbd
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="tbf"></param>
        /// <param name="tbd"></param>
        /// <param name="em"></param>
        /// <param name="selfCenterID"></param>
        /// <param name="selfStationID"></param>
        /// <param name="selfName"></param>
        /// <returns></returns>
        public DataTable Get_LS_CDPF(DateTime start, DateTime end, string tbf, string tbd, E_StatisticsPermisson em, string selfCenterID, string selfStationID, string selfName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                      SELECT 是否有效=case when Isvalid=0 then '无效' else '有效' end ,c.TaskCode as 任务编码,c.PatientOrder AS 序号,Date AS 日期,
                      InvoiceNumber AS 发票号码,PatientName AS 病人姓名,AddressStart AS 起讫地点开始,
                      AddressEnd AS 起讫地点结束 ,OutStationRoadCode AS 出站路码 ,PointRoadCode AS 到点路码 ,
                      ArriveHospitalRoadCode AS 到院路码, ReturnStationRoadCode AS 反站路码 ,OneWayKM AS 单程公里,
                      ChargeKM AS 收费公里,CarFee AS 车费,WaitingFee AS 等候费,EmergencyFee AS 急救费,
                      DrugFeeTotal AS 药品费合计,ExamineFeeTotal AS 检查费合计,
                      ConsumableFeeTotal AS 材料费合计,MeasureFeeTotal AS 救治措施合计 ,ReceivableTotal AS 应收合计,
                      PaidMoney AS 实收金额,ChargePerson AS 收费人,
                      TaskSD AS 流水号 ,ReceivablesPaidInconsistentReasons AS 应收与实收不符的原因
                     ,baidufei AS 摆渡费,c.IMEI AS 收费方式
                      from M_PatientChargeLog  c 
                      left join M_PatientRecord pr on pr.TaskCode =c.TaskCode
                     ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on pr.OutStationCode=ts.编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("Date", start, sb);
            WhereClauseUtility.AddDateTimeLessThan("Date", end, sb);
            WhereClauseUtility.AddStringEqual("InvoiceNumber", tbf, sb);
            WhereClauseUtility.AddStringEqual("TaskSD", tbd, sb);
            if (em == E_StatisticsPermisson.None)
            { return null; }

            else
            {
                if (em == E_StatisticsPermisson.ALL)
                {
                }
                else if (em == E_StatisticsPermisson.CENTER)
                {
                    WhereClauseUtility.AddStringEqual("ts.中心编码", selfCenterID, sb);

                }
                else if (em == E_StatisticsPermisson.STATION)
                {//有误

                    WhereClauseUtility.AddStringEqual("pr.OutStationCode", selfStationID, sb);
                }
                else if (em == E_StatisticsPermisson.SELF)
                {

                    WhereClauseUtility.AddStringEqual("c.ChargePerson", selfName, sb);
                }
            }
            sb.Append(" order by Isvalid desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  病情分类、预报、急救效果、告知签字流水表
        public DataTable Get_LS_BQFL(DateTime beginTime, DateTime endTime, string patientVersion, string stationCode, string agentWorkID, string doctorAndnurse,
                 string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtMeasures, string txtFirstAidEffect,
                 string txtFirstImpression, string txtSendAddress, string formedConsent, string illnessForecast)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select  分中心=tc.名称,
                            分站=ts.名称,
		                    医护人员=mpr.AgentName,
		                    工号=mpr.AgentWorkID,
		                    派单时间=tt.生成任务时刻,
		                    出车地址=mpr.LocalAddress,   
                            联系电话=mpr.ContactTelephone,
						    病情分类=mpr.IllnessClassification,
							急救效果=mpr.FirstAidEffect,
							预报=mpr.IllnessForecast,
							告知签字=case when mpr.FormedConsent=1 then '是' when mpr.FormedConsent=0 then '否' end  
                    from M_PatientRecord  mpr                             
                    left join M_PatientRecordAppend mpra on mpr.TaskCode=mpra.TaskCode and mpr.PatientOrder=mpra.PatientOrder  ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'  
                       and mpr.SubmitLogo=1  ");
            WhereClauseUtility.AddStringLike("mpr.PatientVersion", patientVersion, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationCode, sb);
            WhereClauseUtility.AddStringLike("mpr.AgentName", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", txtFirstImpression, sb);
            WhereClauseUtility.AddStringLike("mpr.SendAddress", txtSendAddress, sb);
            WhereClauseUtility.AddStringEqual("mpr.FormedConsent", formedConsent, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessForecast", illnessForecast, sb);

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  器械检查流水表
        public DataTable Get_QXJC(DateTime beginTime, DateTime endTime, string patientVersion, string stationCode, string agentWorkID, string doctorAndnurse,
                 string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtMeasures, string txtFirstAidEffect,
                 string txtFirstImpression, string txtSendAddress, string formedConsent, string illnessForecast, string machineCheck)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select  distinct   分中心=tc.名称,分站=ts.名称,         
		                    医护人员=mpr.AgentName,
		                    工号=mpr.AgentWorkID,	
							派单时间=tt.生成任务时刻,                    
		                    出车地址=mpr.LocalAddress,   
                            联系电话=mpr.ContactTelephone,
						    心电图诊断=case when mprm.RescueMeasureName='常规心电图检查' then mprm.NumberOfTimes else 0 end,
							十二导联心电图=case when mpra.IF12DaoLian=1  then 1 else 0 end,
							心电监测=case when mprm.RescueMeasureName='心电监测' then mprm.NumberOfTimes else 0 end,
							血糖=case when mprm.RescueMeasureName='葡萄糖测定' then mprm.NumberOfTimes else 0 end,
                            血氧饱和度=case when mprm.RescueMeasureName='指脉氧检测' then mprm.NumberOfTimes else 0 end
							into #temp				
                    from M_PatientRecord  mpr                             
                    left join M_PatientRecordAppend mpra on mpr.TaskCode=mpra.TaskCode and mpr.PatientOrder=mpra.PatientOrder 
                    left join M_PatientRecordMeasure mprm on mpr.TaskCode=mprm.TaskCode and mpr.PatientOrder=mprm.PatientOrder ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'  
                       and mpr.SubmitLogo=1  ");
            WhereClauseUtility.AddStringLike("mpr.PatientVersion", patientVersion, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationCode, sb);
            WhereClauseUtility.AddStringLike("mpr.AgentName", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", txtFirstImpression, sb);
            WhereClauseUtility.AddStringLike("mpr.SendAddress", txtSendAddress, sb);
            WhereClauseUtility.AddStringEqual("mpr.FormedConsent", formedConsent, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessForecast", illnessForecast, sb);

            sb.Append("  order by 派单时间 ");
            sb.Append(@"  select 分中心,分站,医护人员,工号,派单时间,出车地址,联系电话,  	 
							心电图诊断=sum(心电图诊断),
							十二导联心电图=sum(十二导联心电图),
							心电监测=sum(心电监测),
							血糖=sum(血糖),
                            血氧饱和度=sum(血氧饱和度)	
							from #temp    where 1=1 ");
            if (machineCheck == "" || machineCheck == "请选择")
            { sb.Append(" and 1=1 "); }
            if (machineCheck == "常规心电图检查")
            { sb.Append(" and 心电图诊断>=1 "); }
            if (machineCheck == "十二导联心电图")
            { sb.Append(" and 十二导联心电图=1 "); }
            if (machineCheck == "心电监测")
            { sb.Append(" and 心电监测>=1 "); }
            if (machineCheck == "葡萄糖测定")
            { sb.Append(" and 血糖>=1 "); }
            if (machineCheck == "指脉氧检测")
            { sb.Append(" and 血氧饱和度>=1 "); }
            sb.Append(@" group by 分中心,分站,医护人员,工号,派单时间, 出车地址,联系电话   	       
					     drop table #temp ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  拒绝类病历流水表
        public DataTable Get_LS_JJ(DateTime beginTime, DateTime endTime, string patientVersion, string stationCode, string agentWorkID, string doctorAndnurse,
                 string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtMeasures, string txtFirstAidEffect,
                 string txtFirstImpression, string txtSendAddress, string formedConsent, string illnessForecast)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select  分中心=tc.名称,
                            分站=ts.名称,
		                    医护人员=mpr.AgentName,
		                    工号=mpr.AgentWorkID,
		                    派单时间=tt.生成任务时刻,
		                    出车地址=mpr.LocalAddress,   
                            联系电话=mpr.ContactTelephone,
						    拒绝项目1=case when mpr.IllnessClassification='拒绝提供病史' then '拒绝提供病史,' else '' end,
							拒绝项目2=case when mpr.IFRefuseTreatment='拒绝治疗'  then '拒绝治疗,' else '' end,
							拒绝项目3=case when mpra.PhysicalExaminationChoose='拒查' then '体检拒查,' else '' end,
							拒绝项目4=case when mpra.BloodOxygenSaturationSelect='拒查' and mpra.BloodOxygenSaturationSelect='拒查' 
							 and mpra.BloodSugarSelect='拒查' then '器械检查拒查,' when mpra.ECGImpressionSelect='拒查' then '心电图印象拒查,'
							 when mpra.BloodSugarSelect='拒查' then '血糖拒查,' when mpra.BloodOxygenSaturationSelect='拒查' then '血氧饱和度拒查,'
							 else '' end							
					into #temp 				
                    from M_PatientRecord  mpr                             
                    left join M_PatientRecordAppend mpra on mpr.TaskCode=mpra.TaskCode and mpr.PatientOrder=mpra.PatientOrder 
                     ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'   and mpr.SubmitLogo=1
                        and(mpr.IllnessClassification='拒绝提供病史' or mpr.IFRefuseTreatment='拒绝治疗' or mpra.PhysicalExaminationChoose='拒查'
			            or mpra.ECGImpressionSelect='拒查' or mpra.BloodSugarSelect='拒查' or mpra.BloodOxygenSaturationSelect='拒查') ");
            WhereClauseUtility.AddStringLike("mpr.PatientVersion", patientVersion, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationCode, sb);
            WhereClauseUtility.AddStringLike("mpr.AgentName", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", txtFirstImpression, sb);
            WhereClauseUtility.AddStringLike("mpr.SendAddress", txtSendAddress, sb);
            WhereClauseUtility.AddStringEqual("mpr.FormedConsent", formedConsent, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessForecast", illnessForecast, sb);

            sb.Append(@" select 分中心,分站,医护人员,工号,派单时间, 出车地址,联系电话,拒绝项目=拒绝项目1+拒绝项目2+拒绝项目3+拒绝项目4    	                           
						 from #temp 
						 drop table #temp ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  药品使用流水表
        public DataTable Get_LS_YPSY(DateTime beginTime, DateTime endTime, string patientVersion, string stationCode, string agentWorkID, string doctorAndnurse,
                 string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtMeasures, string txtFirstAidEffect,
                 string txtFirstImpression, string txtSendAddress, string formedConsent, string illnessForecast, string nameProblem, string drugName)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                    select distinct 分中心=tc.名称,
                            分站=ts.名称,
		                    医护人员=mpr.AgentName,
		                    工号=mpr.AgentWorkID,
		                    派单时间=tt.生成任务时刻,
		                    出车地址=mpr.LocalAddress,   
                            联系电话=mpr.ContactTelephone,
						    用药情况= mprr.Drugs  
							into #temp					
                    from M_PatientRecord  mpr                             
                    left join M_PatientRecordAppend mpra on mpr.TaskCode=mpra.TaskCode and mpr.PatientOrder=mpra.PatientOrder 
                    left join M_PatientRecordRescue mprr on mpr.TaskCode=mprr.TaskCode and mpr.PatientOrder=mprr.PatientOrder ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'  
                       and mpr.SubmitLogo=1  and mprr.Drugs is not null and mprr.Drugs!='' 
					   ");
            WhereClauseUtility.AddStringLike("mpr.PatientVersion", patientVersion, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationCode, sb);
            WhereClauseUtility.AddStringLike("mpr.AgentName", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", txtFirstImpression, sb);
            WhereClauseUtility.AddStringLike("mpr.SendAddress", txtSendAddress, sb);
            WhereClauseUtility.AddStringEqual("mpr.FormedConsent", formedConsent, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessForecast", illnessForecast, sb);
            //查询条件：医护人员姓名是否异常
            if (nameProblem == "" || nameProblem == "-1")
            { sb.Append(" and 1=1 "); }
            if (nameProblem == "1")
            { sb.Append(" and (mpr.DoctorAndNurse='无' or LEN(mpr.DoctorAndNurse)>4 or LEN(mpr.DoctorAndNurse)<1 ) "); }
            if (nameProblem == "0")
            { sb.Append(" and  LEN(mpr.DoctorAndNurse)<=4 and LEN(mpr.DoctorAndNurse)>1 "); }
            sb.Append(" order by 派单时间 ");
            sb.Append(@"  select 分中心,分站,医护人员,工号,派单时间,出车地址,联系电话,
					   stuff((select ','+用药情况  from #temp t2 where t2.派单时间=t1.派单时间 for xml path('')),1,1,'') as 用药情况 from #temp t1 
                       where 1=1 ");
            //查询条件：药品名称  
            if (drugName != "" && drugName != "--请选择--")
            { sb.Append(" and charindex('" + drugName + "',用药情况)>0 "); }
            sb.Append(@"  group by 分中心,分站,医护人员,工号,派单时间,出车地址,联系电话
					      drop table #temp ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 车辆燃油情况表（车管科统计）
        public DataTable Get_CLRYQK(DateTime beginTime, DateTime endTime, string centerID, string stationID, string actualCode, string ambulanceNumber)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select   
                                 加油车号1=ocr.ActualCode,加油车号2=ocr.AmbulanceNumber,
                                 加油量=Convert(decimal(18,2),ocr.OilMass),月=datepart(month,ocr.RefuelTime),日=datepart(day,ocr.RefuelTime),
                                 加油日期=ocr.RefuelTime,上次加油路码=Convert(decimal(18,2),ocr.LastGasPathCode),      
                                 本次加油路码=Convert(decimal(18,2),ocr.GasPathCode),行驶公里=Convert(decimal(18,2),ocr.DrivingKM)
                                 ,加油人=ocr.RefuelPerson,凭证编号=ocr.ProofNumber                                    
                        from C_OilCardRefuel ocr 
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("ocr.RefuelTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("ocr.RefuelTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("ocr.CenterID", centerID, sb);
            WhereClauseUtility.AddStringEqual("ocr.StationID", stationID, sb);
            WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", actualCode, sb);
            WhereClauseUtility.AddStringEqual("ocr.AmbulanceCode", ambulanceNumber, sb);
            sb.Append(" order by 加油日期  ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];

        }
        #endregion

        #region 车辆油耗情况表汇总（车管科统计）
        public DataTable Get_CLYHQKHZ(DateTime beginTime, DateTime endTime, string centerID, string stationID, string actualCode, string ambulanceNumber)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"  select  分中心=tc.名称,分站=ts.名称,车号=ocr.ActualCode,   
                                  公里数=sum(isnull(Convert(decimal(18,2),ocr.DrivingKM),0))
                                  ,用油数=sum(isnull(Convert(decimal(18,2),ocr.OilMass),0))                                    
                          from C_OilCardRefuel ocr 
                          left join C_Ambulance ca on ca.AmbulanceCode=ocr.AmbulanceCode
                        ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ca.StationCode=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddDateTimeGreaterThan("ocr.RefuelTime", beginTime, sb);
            WhereClauseUtility.AddDateTimeLessThan("ocr.RefuelTime", endTime, sb);
            WhereClauseUtility.AddStringEqual("ca.CenterCode", centerID, sb);
            WhereClauseUtility.AddStringEqual("ca.StationCode", stationID, sb);
            WhereClauseUtility.AddStringEqual("ca.AmbulanceCode", actualCode, sb);
            WhereClauseUtility.AddStringEqual("ca.AmbulanceCode", ambulanceNumber, sb);
            sb.Append(" group by  ocr.ActualCode,tc.名称,ts.名称 ");
            sb.Append(" order by  tc.名称,ts.名称 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];

        }
        #endregion

        #region 物资/措施信息修改痕迹流水表
        public DataTable Get_LS_WZXGHJ(DateTime start, DateTime end, string material, string modifyItem)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  物资名称=MName,修改项=ModifyItem,原值=OriginalValue,
                                现值=NewValue,修改人=ModifyPerson,修改时间=ModifyTime         
                        from I_MaterialTrace  
                        where  ModifyTime>='" + start + "' and  ModifyTime<'" + end + "' ");
            WhereClauseUtility.AddStringEqual("MID", material, sb);
            WhereClauseUtility.AddStringLike("ModifyItem", modifyItem, sb);
            sb.Append(" order by ModifyTime desc ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        //取物资/措施名称和编码
        public object GetMaterial()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     select   ID,Name     from I_Material  
                     where  IsActive=1 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["ID"].ToString();
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }
        //取物资基础信息表的字段说明（I_Material表）
        public object GetDescription()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@" SELECT   Name =isnull(props.[value],'')
                         FROM syscolumns cols 
                         inner join sysobjects objs on cols.id= objs.id and  objs.xtype='U' and  objs.name<>'dtproperties' 
                         left join sys.extended_properties props on cols.id=props.major_id and cols.colid=props.minor_id 
                         WHERE objs.name='I_Material' ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }

        #endregion

        #region 急救评分流水表

        public DataTable Get_LS_JJPF(DateTime beginTime, DateTime endTime, string patientVersion, string stationCode, string agentWorkID, string doctorAndnurse,
              string txtCenter, string txtDiseasesClassification, string txtIllnessClassification, string txtDeathCase, string txtMeasures, string txtFirstAidEffect,
              string txtFirstImpression, string txtSendAddress, string formedConsent, string ScoreType)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                   select distinct 
   
	                分中心=tc.名称,
	                 分站=ts.名称,
	                医护人员=mpr.DoctorAndNurse,
	                工号=mpr.AgentWorkID,
	                   派单时间=tt.生成任务时刻,
	                出车地址=mpr.LocalAddress,   
	                联系电话=mpr.ContactTelephone,
    	    case when  isnull(mpra.GCSScore,0) >0 and  isnull(mpra.TIScore,0) =0  and isnull(mpra.ApgarScore,0)=0  then  'GCS评分'
			        when isnull(mpra.TIScore,0) >0  and  isnull(mpra.GCSScore,0) =0  and isnull(mpra.ApgarScore,0)=0  then  'TI评分'
			        when isnull(mpra.ApgarScore,0)>0  and  isnull(mpra.GCSScore,0) =0  and isnull(mpra.TIScore,0)=0   then  'Apgar评分'
			        when isnull(mpra.ApgarScore,0)=0  and  isnull(mpra.GCSScore,0) >0  and isnull(mpra.TIScore,0)>0   then  'GCS评分,TI评分'
			        when isnull(mpra.ApgarScore,0)>0  and  isnull(mpra.GCSScore,0)>0  and isnull(mpra.TIScore,0)=0   then  'GCS评分,Apgar评分'
			        when isnull(mpra.ApgarScore,0)>0  and  isnull(mpra.GCSScore,0) =0  and isnull(mpra.TIScore,0)>0   then  'Apgar评分,TI评分'
			        when isnull(mpra.ApgarScore,0)=0  and  isnull(mpra.GCSScore,0) =0  and isnull(mpra.TIScore,0)>0   then  ' '
			        else  ''   end  as  评分项目 ,
	
	 isnull(mpra.GCSScore,0)  as GCS分值,
	isnull(mpra.TIScore,0) as TI分值,
	isnull(mpra.ApgarScore,0) as Apgar分值,
	mpr.DiseasesClassification + mpr.DiseasesClassificationSupplement  as  病种分类,
	case when ( CHARINDEX (',',mpra.FirstImpression) > 0)   then   substring(mpra.FirstImpression,1,len(mpra.FirstImpression)-1)   + ' '+  mpra.FirstImpressionSupplement +mpra.FirstImpressionDoubt
	else mpra.FirstImpression  + '  '+  mpra.FirstImpressionSupplement +mpra.FirstImpressionDoubt end   as 初步印象

				
	from M_PatientRecord  mpr                             
	left join M_PatientRecordAppend mpra on mpr.TaskCode=mpra.TaskCode and mpr.PatientOrder=mpra.PatientOrder 
	left join M_PatientRecordRescue mprr on mpr.TaskCode=mprr.TaskCode and mpr.PatientOrder=mprr.PatientOrder 
 ");
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on mpr.TaskCode=tt.任务编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on tt.分站编码=ts.编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'  
                       and mpr.SubmitLogo=1  ");
            WhereClauseUtility.AddStringLike("mpr.PatientVersion", patientVersion, sb);
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationCode, sb);
            WhereClauseUtility.AddStringLike("mpr.DoctorAndNurse", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddStringEqual("mpr.DiseasesClassification", txtDiseasesClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.IllnessClassification", txtIllnessClassification, sb);
            WhereClauseUtility.AddStringEqual("mpr.DeathCase", txtDeathCase, sb);
            WhereClauseUtility.AddStringEqual("mpr.FirstAidEffect", txtFirstAidEffect, sb);
            WhereClauseUtility.AddStringLike("mpra.FirstImpression", txtFirstImpression, sb);
            WhereClauseUtility.AddStringLike("mpr.SendAddress", txtSendAddress, sb);
            WhereClauseUtility.AddStringEqual("mpr.FormedConsent", formedConsent, sb);
            if (ScoreType.Length > 0)
            {
                switch (ScoreType)
                {
                    case "GCSScore": sb.Append(@"  and mpra.GCSScore> 0 ");
                        break;
                    case "TIScore": sb.Append(@"  and mpra.TIScore> 0 ");
                        break;
                    case "ApgarScore": sb.Append(@"  and mpra.ApgarScore> 0 ");

                        break;
                    default: break;
                }
            }
            sb.Append(@" group by  tc.名称, ts.名称, mpr.DoctorAndNurse, mpr.AgentWorkID, tt.生成任务时刻 ,mpr.LocalAddress , mpr.ContactTelephone
  ,mpra.GCSScore,mpra.TIScore,mpra.ApgarScore,mpr.DiseasesClassification,mpr.DiseasesClassificationSupplement,mpra.FirstImpression,mpra.FirstImpressionSupplement,mpra.FirstImpressionDoubt    ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }


        #endregion

        #region 救治措施流水表 2016-01-15
        /// <summary>
        ///
        /// </summary>
        /// <param name="str"></param>
        /// <param name="ck"></param>
        /// <param name="fl"></param>
        /// <param name="wz"></param>
        /// <returns></returns>
        public DataTable Get_LSJZCS(DateTime beginTime, DateTime endTime, string stationCode, string agentWorkID, string doctorAndnurse,
                 string txtCenter, string TBXX, string TBDL)
        {
            //StringBuilder sb = new StringBuilder();
//            sb.Append(@"
//  select tc.名称 as 分中心, pr.Station as 分站, pr.DoctorAndNurse as 医护人员, pr.OutStationCode,tc.编码,
//  pr.AgentWorkID as 工号,tt.生成任务时刻 as 派单时间,  pr.ForArea+pr.LocalAddress as 出车地址,pr.ContactTelephone as 联系电话, 
//  STUFF((select distinct ','+prm2.RescueMeasureName 
//   from [M_PatientRecord] pr2  left join [dbo].[M_PatientRecordMeasure] prm2 on pr2.TaskCode =prm2.TaskCode  
//    left join [dbo].[TDictionary] td2 on prm2.OtherTypeID=td2.ID  left join Anchor120V7.dbo.TStation ts2 on ts2.名称=pr2.Station  
//	left join Anchor120V7.dbo.TCenter tc2 on tc2.编码=ts2.中心编码       left join Anchor120V7.dbo.TTask tt2 on tt2.任务编码=pr2.TaskCode 
//	     where tc.名称=tc2.名称 and pr.Station=pr2.Station and pr.DoctorAndNurse=pr2.DoctorAndNurse and     
//		  pr.AgentWorkID=pr2.AgentWorkID  and tt.生成任务时刻=tt2.生成任务时刻 and   
//		     pr.ForArea+pr.LocalAddress=pr2.ForArea+pr2.LocalAddress and pr.ContactTelephone=pr2.ContactTelephone  and  pr.OutStationCode=pr2.OutStationCode and tc.编码=tc2.编码
//			  FOR XML PATH('')),1,1,'') as 详细救治措施, STUFF((select distinct ','+td1.Name 
//			   from [M_PatientRecord] pr1  
//			   left join [dbo].[M_PatientRecordMeasure] prm1 on pr1.TaskCode =prm1.TaskCode  
//			    left join [dbo].[TDictionary] td1 on prm1.OtherTypeID=td1.ID  
//				 left join Anchor120V7.dbo.TStation ts1 on ts1.名称=pr1.Station  
//				   left join Anchor120V7.dbo.TCenter tc1 on tc1.编码=ts1.中心编码        
//				   left join Anchor120V7.dbo.TTask tt1 on tt1.任务编码=pr1.TaskCode     
//				     where tc.名称=tc1.名称 and pr.Station=pr1.Station and pr.DoctorAndNurse=pr1.DoctorAndNurse 
//					 and tt.生成任务时刻=tt1.生成任务时刻 and      pr.AgentWorkID=pr1.AgentWorkID  and    
//					   pr.ForArea+pr.LocalAddress=pr1.ForArea+pr1.LocalAddress and pr.ContactTelephone=pr1.ContactTelephone and pr.OutStationCode=pr1.OutStationCode and tc.编码=tc1.编码
//					    FOR XML PATH('')),1,1,'') as 救治措施大类 
//						from  [M_PatientRecord] pr left join [dbo].[M_PatientRecordMeasure] prm on pr.TaskCode =prm.TaskCode  
//						  left join [dbo].[TDictionary] td on prm.OtherTypeID=td.ID 
//						     left join Anchor120V7.dbo.TStation ts on ts.名称=pr.Station 
//							 left join Anchor120V7.dbo.TCenter tc on tc.编码=ts.中心编码  
//							 left join Anchor120V7.dbo.TTask tt on tt.任务编码=pr.TaskCode   
//"
//);

            //add2021-05-28 plq 库名改为配置
            StringBuilder sb = new StringBuilder();
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);//链接调度库
            sb.Append(@"
                  select tc.名称 as 分中心, pr.Station as 分站, pr.DoctorAndNurse as 医护人员, pr.OutStationCode,tc.编码,
                  pr.AgentWorkID as 工号,tt.生成任务时刻 as 派单时间,  pr.ForArea+pr.LocalAddress as 出车地址,pr.ContactTelephone as 联系电话, 
                  STUFF((select distinct ','+prm2.RescueMeasureName 
                  from [M_PatientRecord] pr2  
                  left join [dbo].[M_PatientRecordMeasure] prm2 on pr2.TaskCode =prm2.TaskCode  
                  left join [dbo].[TDictionary] td2 on prm2.OtherTypeID=td2.ID ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts2 on ts2.名称=pr2.Station ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc2 on tc2.编码=ts2.中心编码  ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt2 on tt2.任务编码=pr2.TaskCode  ");
            sb.Append(@"
	              where tc.名称=tc2.名称 and pr.Station=pr2.Station and pr.DoctorAndNurse=pr2.DoctorAndNurse 
                  and pr.AgentWorkID=pr2.AgentWorkID  and tt.生成任务时刻=tt2.生成任务时刻 
                  and pr.ForArea+pr.LocalAddress=pr2.ForArea+pr2.LocalAddress and pr.ContactTelephone=pr2.ContactTelephone  
                  and  pr.OutStationCode=pr2.OutStationCode and tc.编码=tc2.编码 FOR XML PATH('')),1,1,'') as 详细救治措施
                  , STUFF((select distinct ','+td1.Name 
			      from [M_PatientRecord] pr1  
			      left join [dbo].[M_PatientRecordMeasure] prm1 on pr1.TaskCode =prm1.TaskCode  
			      left join [dbo].[TDictionary] td1 on prm1.OtherTypeID=td1.ID  ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts1 on ts1.名称=pr1.Station ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc1 on tc1.编码=ts1.中心编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt1 on tt1.任务编码=pr1.TaskCode ");
            sb.Append(@"
				  where tc.名称=tc1.名称 and pr.Station=pr1.Station and pr.DoctorAndNurse=pr1.DoctorAndNurse 
				  and tt.生成任务时刻=tt1.生成任务时刻 and  pr.AgentWorkID=pr1.AgentWorkID  
                  and pr.ForArea+pr.LocalAddress=pr1.ForArea+pr1.LocalAddress and pr.ContactTelephone=pr1.ContactTelephone 
                  and pr.OutStationCode=pr1.OutStationCode and tc.编码=tc1.编码 FOR XML PATH('')),1,1,'') as 救治措施大类 
				  from  [M_PatientRecord] pr 
                  left join [dbo].[M_PatientRecordMeasure] prm on pr.TaskCode =prm.TaskCode  
				  left join [dbo].[TDictionary] td on prm.OtherTypeID=td.ID   ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ts.名称=pr.Station ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码 ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on tt.任务编码=pr.TaskCode ");

            sb.Append(" where tt.生成任务时刻 >='" + beginTime + @"' and tt.生成任务时刻 <'" + endTime + @"'");
            WhereClauseUtility.AddInSelectQuery("tc.编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("pr.OutStationCode", stationCode, sb);
            WhereClauseUtility.AddStringLike("pr.DoctorAndNurse", doctorAndnurse, sb);
            WhereClauseUtility.AddStringEqual("pr.AgentWorkID", agentWorkID, sb);
            WhereClauseUtility.AddInSelectQuery("prm.RescueMeasureCode", TBXX, sb);
            WhereClauseUtility.AddStringInSelectQuery("td.ID", TBDL, sb);
            sb.Append(@"group by  tc.名称,  pr.Station , pr.DoctorAndNurse , 
  pr.AgentWorkID ,tt.生成任务时刻 ,  pr.ForArea+pr.LocalAddress ,pr.ContactTelephone ,pr.OutStationCode,tc.编码 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region  非生产用车流水表
        public DataTable Get_LS_FSCYC(DateTime dateStart, DateTime dateEnd, string centerID, string stationID, string workID)
        {
            StringBuilder sb = new StringBuilder();
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(@"select AgentWorkID as 填写人工号,ReportDate as 日报日期,StationName as 分站,tc.名称 as 分中心
                               ,AmbulanceNumber as 车辆号码,AmbulanceCode as 车辆编号,backup3 as 备注
                               ,OffDutyKM as 下班路码,OnDutyKM as 上班路码,DayKM as 非生产公里数,td.Name as 非生产原因
                               ,RefuelLitre as 油耗,RefuelInvoiceNumber as 加油发票号,OffDutyDipstick as 油尺下班
                               ,OnDutyDipstick as 油尺上班,OilConsumption as 非生产油耗,dr.Stretcher2WorkID as 随车人员1,dr.Stretcher3WorkID as 随车人员2 
                        from D_DriverReport dr  
                     ");
            sb.Append(" left join TDictionary  td on dr.backup4 = td.ID   ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=dr.CenterCode ");
            sb.Append(" where BanCi='非生产用车'");
            WhereClauseUtility.AddDateTimeGreaterThan("dr.ReportDate", dateStart, sb);
            WhereClauseUtility.AddDateTimeLessThan("dr.ReportDate", dateEnd, sb);
            WhereClauseUtility.AddInSelectQuery("tc.编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("dr.StationCode", stationID, sb);
            //2016-7-8 zch 修改了参数workID 增加对应了随车人员1，2
            if (workID != null && workID.Length > 0)
            {
                sb.Append("and (dr.AgentWorkID ='" + workID + "' or dr.Stretcher2WorkID='" + workID + "' or dr.Stretcher3WorkID ='" + workID + "') ");
            }
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region  异常结束流水表 2016-06-21  新增
        //2016-11-25 周志猛 将“车到不送”改为了“车到未送”
        public DataTable Get_LS_YCJS(DateTime beginTime, DateTime endTime, string txtCenter, string stationID, string doctor,
                                     string nurse, string driver, string stretcher, string emptyType)
        {
            StringBuilder sb = new StringBuilder();
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            sb.Append(@"select  分中心=tc.名称,分站=ts.名称,
                        医护人员=isnull( ");
            sb.Append(builder.InitialCatalog).Append(@".dbo.GetNameWorkStr(tt.任务编码,4),'')+isnull( ");
            sb.Append(builder.InitialCatalog).Append(@".dbo.GetNameWorkStr(tt.任务编码,5),''),
                        司机=isnull( ");
            sb.Append(builder.InitialCatalog).Append(@".dbo.GetNameWorkStr(tt.任务编码,3),''),
                        担架员=isnull( ");
            sb.Append(builder.InitialCatalog).Append(@".dbo.GetNameWorkStr(tt.任务编码,6),''),                       
                        事件类型=mpr.PatientVersion,异常结束类型=case when mpr.PatientVersion='空车' then mpr.EmptyReason  when mpr.SendAddress='车到未送' then mpr.SendAddress else '' end,
                        派车时刻=tt.生成任务时刻,联系电话=mpr.ContactTelephone,现场地址=mpr.LocalAddress,
                        更改后时间1=case when CONVERT(varchar(19),isnull(tt.出车时刻,''),120) <> CONVERT(varchar(19),isnull(mpr.DrivingTime,''),120) then isnull(mpr.DrivingTime,null) else null end
                        ,更改原因1=isnull(mpr.DrivingTimeSupplement,''),
                        更改后时间2=case when CONVERT(varchar(19),isnull(tt.到达现场时刻,''),120) <>CONVERT(varchar(19),isnull(mpr.ArriveSceneTime,''),120) then isnull(mpr.ArriveSceneTime,null) else null end
                        ,更改原因2=isnull(mpr.ArriveSceneTimeSupplement,''),
                        更改后时间3=case when  CONVERT(varchar(19),isnull(tt.离开现场时刻,''),120) <>CONVERT(varchar(19),isnull(mpr.LeaveSceneTime,''),120) then isnull(mpr.LeaveSceneTime,null) else null end
                        ,更改原因3=isnull(mpr.LeaveSceneTimeSupplement,''),
                        更改后时间4=case when CONVERT(varchar(19),isnull(tt.到达医院时刻,''),120) <>CONVERT(varchar(19),isnull(mpr.ArriveDestinationTime,''),120) then isnull(mpr.ArriveDestinationTime,null) else null end
                        ,更改原因4=isnull(mpr.ArriveDestinationTimeSupplement,''),
                        应收车费=isnull(mpc.CarFee,0),
                        应收医疗费=isnull(mpc.EmergencyFee,0)+isnull(mpc.DrugFeeTotal,0)+isnull(mpc.ExamineFeeTotal,0)+isnull(mpc.ConsumableFeeTotal,0)+isnull(mpc.MeasureFeeTotal,0),
                        实收金额=isnull(mpc.PaidMoney,0)
                        from M_PatientRecord mpr 
                        left join M_PatientCharge  mpc on mpc.TaskCode=mpr.TaskCode ");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on tt.任务编码=mpr.TaskCode");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ts.编码=tt.分站编码");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TCenter tc on tc.编码=ts.中心编码");
            sb.Append(@" where tt.生成任务时刻>='" + beginTime + "' and tt.生成任务时刻<'" + endTime + @"' and mpr.SubmitLogo=1 
                                    and ((mpr.PatientVersion ='救治' and mpr.SendAddress='车到未送') or mpr.PatientVersion= '空车' ) ");
            WhereClauseUtility.AddInSelectQuery("tc.编码", txtCenter, sb);
            WhereClauseUtility.AddInSelectQuery("ts.编码", stationID, sb);
            WhereClauseUtility.AddStringLike("mpr.DoctorAndNurse", doctor, sb);
            WhereClauseUtility.AddStringLike("mpr.DoctorAndNurse", nurse, sb);
            WhereClauseUtility.AddStringLike("mpr.Driver", driver, sb);
            WhereClauseUtility.AddStringLike("mpr.StretcherBearersI", stretcher, sb);
            if (emptyType == "" || emptyType == "请选择")
            { sb.Append(" and 1=1 "); }
            if (emptyType == "1")
            { sb.Append(" and mpr.EmptyReason='途中召回' "); }
            if (emptyType == "2")
            { sb.Append(" and mpr.EmptyReason='车到人走' "); }
            if (emptyType == "3")
            { sb.Append(" and mpr.EmptyReason='车到不要（未诊治）' "); }
            if (emptyType == "4")
            { sb.Append(" and mpr.EmptyReason='突发事件' "); }
            if (emptyType == "5")
            { sb.Append(" and mpr.EmptyReason='其他' "); }
            if (emptyType == "6")
            { sb.Append(" and mpr.SendAddress='车到未送' "); }
            sb.Append(" order by tt.生成任务时刻 desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region 取全部人员信息   2016-7-8 zch
        /// <summary>
        /// 返回所有人员的工号和姓名
        /// </summary>
        /// <returns></returns>
        public object getAllPersonWorkID()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                     select WorkCode,Name   from P_User  u
                     where u.IsActive=1 ");

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["WorkCode"].ToString();
                    info.Name = dr["Name"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

        #region 取任务异常结束原因
        private List<CommonTree> m_ModelList;
        public object GetTaskReason()
        {
            m_ModelList = GetTreeInfoList();
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
select  编码,名称 from TZTaskAbendReason where 上级编码=0 and 是否有效=1");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CommonTree> list = new List<CommonTree>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CommonTree info = new CommonTree();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CommonTree();
                    info.id = dr["编码"].ToString();
                    info.text = dr["名称"].ToString();
                    info.children = GetChildren(info.id, m_ModelList);
                    list.Add(info);
                }
            }
            return list;

        }
        private List<CommonTree> GetTreeInfoList()
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(" select * from TZTaskAbendReason where 是否有效=1  order by 顺序号 ");
                DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
                List<CommonTree> list = new List<CommonTree>();
                if (ds.Tables[0].Rows.Count > 0)
                {
                    CommonTree info = new CommonTree();
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        info = new CommonTree();
                        info.id = dr["编码"].ToString();
                        info.text = dr["名称"].ToString();
                        info.ParentID = dr["上级编码"].ToString();
                        list.Add(info);
                    }
                }
                return list;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        private List<CommonTree> GetChildren(string parentID, List<CommonTree> list)
        {
            List<CommonTree> children = new List<CommonTree>();
            CommonTree treeInfo = new CommonTree();
            List<CommonTree> newlist = list.Where(t => t.ParentID == parentID).ToList();
            foreach (CommonTree info in newlist)
            {
                treeInfo = new CommonTree();
                treeInfo.id = info.id.ToString();
                treeInfo.text = info.text;
                treeInfo.ParentID = parentID;
                treeInfo.children = GetChildren(treeInfo.id, m_ModelList);
                if (treeInfo.children.Count > 0)
                {
                    treeInfo.state = "closed";
                }
                else
                {
                    treeInfo.state = "open";
                }
                children.Add(treeInfo);
            }
            return children;
        }
        #endregion

        #region 根据人员类型取人员信息   20160922 刘爱青
        /// <summary>
        /// 返回人员的编码和姓名
        /// </summary>
        /// <returns></returns>
        public object GetPersonForType(string RoleID, string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
select 编码,姓名 from TPerson  u where u.是否有效=1 ");
            WhereClauseUtility.AddStringEqual("类型编码", RoleID, sb);
            WhereClauseUtility.AddStringEqual("ts.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
order by 姓名 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["姓名"].ToString();
                    list.Add(info);
                }
            }
            return list;
        }
        #endregion

        #region 取国籍，民族
        //取国籍
        public object GetNational()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZNational
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        //取民族
        public object GetFolk()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZFolk
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取事件来源
        public object GetEventSource()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAlarmEventOrigin
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取区域，事故类型，事故等级
        //取区域
        public object GetArea()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZArea
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        //取事故类型
        public object GetAccidentType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAccidentType
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        //取事故等级
        public object GetAccidentLevel()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAccidentLevel
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 急救中心任务流水表
        /// <summary>
        /// 急救中心任务流水表 2016-12-08 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_JJZXRW(DateTime beginTime, DateTime endTime, string name, string centerID, string stationID, string doctorAndNurse, string driver, string stretcherBearersI, string alarmReason,
                                        string medicalJudge, string localAddress, string sendAddress, string dispatcher, string time, string area, string result, string banCi, string helpType, string arrivalTime, string street, string eventOrigin, string eventDispatchCenterID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch
            sb.Append(EnumSqlAppnd.TZTaskAbendReason());//2020-12-02 zch
            //add2021-07-14 plq 患者姓名改从病历中取，新增性别、年龄字段
            sb.Append(@"select
                            tt.任务编码
                            ,tt.事件编码
                            ,tt.任务流水号
                            --,姓名=(tac.患者姓名)
                            ,姓名=mpr.Name,性别=mpr.Sex,年龄=mpr.Age+mpr.AgeType
                            ,患者地址=tac.现场地址
                            ,主诉=tac.主诉
                            ,挂机时刻= case when tac.挂起时刻='' then null else convert(varchar(8),结束时刻,114) end
                            ,挂单时刻= tac.挂起时刻
                            ,挂单时长=DATEDIFF(MINUTE,tac.挂起时刻,发送指令时刻)
                            ,电话=tac.联系电话
                            ,受理时刻=tae.首次受理时刻
                            ,派车时刻=convert(varchar(8),首次派车时刻,114)
                            ,发送指令时刻=convert(varchar(8),发送指令时刻,114)
                            ,出车时刻=convert(varchar(8),出车时刻,114)
                            ,到达现场时刻=convert(varchar(8),到达现场时刻,114)
                            ,返回站中时刻=convert(varchar(8),返回站中时刻,114)
                            ,到达医院时刻=convert(varchar(8),到达医院时刻,114)
                            ,收到指令时刻=convert(varchar(8),接收命令时刻,114)
                            ,病家上车时刻=convert(varchar(8),离开现场时刻,114)
                            ,车辆=ta.车牌号码
                            ,反应时间=datediff(MINUTE,tt.接收命令时刻,tt.到达现场时刻)
                            ,到达现场时间=datediff(MINUTE,tt.出车时刻,tt.到达现场时刻)
                            ,现场处理时间=datediff(MINUTE,tt.到达现场时刻,tt.离开现场时刻)
                            ,送往地点=tac.送往地点
                            ,司机=tt.司机
                            ,医生=tt.医生
                            ,护士=tt.护士
                            ,送院时间=DATEDIFF(MINUTE,tt.离开现场时刻,tt.到达医院时刻)
                            ,收费=mpc.PaidMoney
                            ,欠费=(case when mpc.ReceivableTotal>=mpc.PaidMoney then mpc.ReceivableTotal-mpc.PaidMoney else 0 end)
                            ,出车结果=case when tt.是否正常结束=1 then '正常结束'
                            when tt.是否正常结束=0 and tt.异常结束原因编码 in (@已救治,@死亡不送,@病人不去,@车到人走) then '放空车'
                            when tt.是否正常结束=0 and tt.异常结束原因编码 not in (@已救治,@死亡不送,@病人不去,@车到人走,-1) then '中止任务'
                            else '其他'
                            end
                            ,所属分站=ts.名称
                            ,驶向现场时刻=convert(varchar(8),出车时刻,114)
                            ,途中待命时刻 = convert(varchar(8),完成时刻,114)
                            ,班次=case when convert(varchar(10),tt.生成任务时刻,114)>'08:00:00' and convert(varchar(10),tt.生成任务时刻,114)<'20:00:00' then '白班' else '夜班' end
                            ,PatientVersion= mpr.PatientVersion
                            ,DiseasesClassification=mpr.DiseasesClassification
                            ,IllnessClassification=mpr.IllnessClassification
                            ,中心编码=ts.中心编码
                            ,分站编码=tt.分站编码
                            ,判断=tac.病种判断
                            ,担架工=tt.担架工
                            ,区域=tae.区域
                            ,街道=tae.街道
                            ,受理备注=tac.备注
                            ,调度员=tp.姓名
                            ,超过1分钟受理电话=case when datediff(second,通话时刻,结束时刻)>60 then tp.姓名 else ' ' end
                            ,电话受理时间=DATEDIFF(SECOND,通话时刻,结束时刻)
                            ,表单受理时间=DATEDIFF(SECOND,开始受理时刻,发送指令时刻)
                            ,呼救类型=tzaet.名称
                            ,事件来源=tzaeo.名称
                            ,迟缓放车调度员=case when tae.事件类型编码 in (@救治,@转院) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >5 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 when tae.事件类型编码=@回家 then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 when tae.事件类型编码 in (@转分中心急,@转长途,@其它,@转分中心非,@特殊事件,@跨省,@保障,@送担架) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 ELSE ' ' 
                                                 END
                            ,迟缓接听=case when 振铃时刻!='' and (datediff(second,振铃时刻,通话时刻)>10) then tp.姓名 else  ' ' end 
                                into #temp
                                from dbo.TTask tt
                                left join dbo.TAcceptEvent tac on tt.事件编码=tac.事件编码 and tac.受理序号=tt.受理序号
                                left join dbo.TAlarmEvent tae on tt.事件编码=tae.事件编码
                                left join dbo.TAlarmCall tal on tt.事件编码=tal.事件编码 and tal.是否呼出=0 and tac.呼救电话 = tal.主叫号码
                                --and tal.通话类型编码!=8
                                left join dbo.TAmbulance ta on ta.车辆编码=tt.车辆编码
                                left join dbo.TStation ts on ts.编码=tt.分站编码 ");

            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientCharge mpc on mpc.TaskCode=tt.任务编码 and mpc.PatientOrder=1");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientRecord mpr on mpr.TaskCode=tt.任务编码 and mpr.PatientOrder=1");
            sb.Append(@"
                            left join TPerson tp on tp.编码=tae.首次调度员编码 and tp.类型编码=2
                            left join TZAlarmEventType tzaet on tzaet.编码=tae.事件类型编码
                            left join TZAlarmEventOrigin tzaeo on tzaeo.编码=tae.事件来源编码
                            where tae.首次受理时刻>'" + beginTime + "' and tae.首次受理时刻<'" + endTime + @"' and tae.是否测试=0 ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"
                            select tt.任务编码,收到指令的按键方式,驶向现场的按键方式,到达现场的按键方式,病人上车的按键方式,到达医院的按键方式,途中待命的按键方式,站内待命的按键方式
                            ,tp.工号
                            into #temp2
                            from TTask tt 
                            left join 
                            (select distinct(a.任务编码),驶向现场的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=2 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=2 
                            ) t2 on t2.任务编码=tt.任务编码

                            left join ( select distinct(a.任务编码),到达现场的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=3 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=3 
                            ) t3 on t3.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),病人上车的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=4 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=4 
                            ) t4 on t4.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),到达医院的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=5 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=5 
                            ) t5 on t5.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),途中待命的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=6 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=6 
                            ) t6 on t6.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),站内待命的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=7 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=7 
                            ) t7 on t7.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),收到指令的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=1 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=1 
                            ) t8 on t8.任务编码=tt.任务编码

                            left join TPerson tp on tp.编码=tt.责任调度人编码
                            left join TAlarmEvent tae on tae.事件编码=tt.事件编码
                            where 生成任务时刻>'" + beginTime + "' and 生成任务时刻<='" + endTime + @"'  ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"                

                            select
                            t.姓名,性别,年龄
                            ,任务流水号,患者地址,主诉,超过1分钟受理电话,电话,挂机时刻
                            ,挂单时刻,挂单时长,迟缓放车调度员,迟缓接听
                            ,受理时刻
                            ,发送指令时刻,出车时刻,到达现场时刻
                            ,返回站中时刻,到达医院时刻,途中待命时刻,驶向现场时刻,收到指令时刻,病家上车时刻
                            ,响应时间=case when DATEDIFF(SECOND,收到指令时刻,驶向现场时刻)>0 then DATEDIFF(SECOND,收到指令时刻,驶向现场时刻) else null end
                            ,到达现场时间
                            ,现场处理时间,车辆
                            ,收到指令的按键方式,驶向现场的按键方式
                            ,到达现场的按键方式,病人上车的按键方式
                            ,到达医院的按键方式,途中待命的按键方式
                            ,站内待命的按键方式,反应时间
                            ,交接时间=case when DATEDIFF(MINUTE,到达医院时刻,途中待命时刻)>0 then DATEDIFF(MINUTE,到达医院时刻,途中待命时刻) else null end
                            ,送往地点,司机,医生,护士,调度员,送院时间
                            ,收费,欠费,班次,出车结果
                            ,所属分站,中心编码,分站编码
                            ,判断
                            ,电话受理时间
                            ,担架工,区域
                            ,街道
                            ,受理备注
                            ,工号
                            ,表单受理时间
                            ,呼救类型
                            ,事件来源
                            from #temp t
                            left join #temp2 t2 on t2.任务编码=t.任务编码
                   where 受理时刻>= '" + beginTime + "' and 受理时刻<'" + endTime + @"'  
                            ");
            WhereClauseUtility.AddInSelectQuery("t.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("t.分站编码", stationID, sb);
            WhereClauseUtility.AddStringLike("t.司机", driver, sb);
            WhereClauseUtility.AddStringLike("t.姓名", name, sb);
            WhereClauseUtility.AddStringLike("t.医生", doctorAndNurse, sb);
            WhereClauseUtility.AddStringLike("t.担架工", stretcherBearersI, sb);
            WhereClauseUtility.AddStringLike("t.主诉", alarmReason, sb);
            WhereClauseUtility.AddStringLike("t.判断", medicalJudge, sb);
            WhereClauseUtility.AddStringLike("t.患者地址", localAddress, sb);
            WhereClauseUtility.AddStringLike("t.送往地点", sendAddress, sb);
            WhereClauseUtility.AddStringLike("t.调度员", dispatcher, sb);
            WhereClauseUtility.AddStringEqual("t.区域", area, sb);
            WhereClauseUtility.AddStringLike("t.街道", street, sb); //add2021-06-22 plq 增加街道查询条件
            WhereClauseUtility.AddStringEqual("t.出车结果", result, sb);
            WhereClauseUtility.AddStringEqual("t.班次", banCi, sb);
            WhereClauseUtility.AddStringEqual("t.呼救类型", helpType, sb);
            WhereClauseUtility.AddStringEqual("t.事件来源", eventOrigin, sb); //事件来源列及筛选条件 add2021-07-03 plq
            if (time == "")
            { }
            else
            { sb.Append(@" and 电话受理时间>'" + time + @"'"); }
            //add2020-07-13 plq 增加到达现场时间大于XX(分) 筛选项
            if (arrivalTime == "")
            { }
            else
            { sb.Append(@" and 到达现场时间>'" + arrivalTime + @"'"); }

            sb.Append(@" order by 受理时刻
                         drop table #temp
                         drop table #temp2
                      ");
            
            
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        /// <summary>
        /// 急救中心迟缓放车任务流水表 20200427 plq 
        /// 在上方急救中心任务流水任务中 只取 迟缓放车 流水任务
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_JJZXCHFCRW(DateTime beginTime, DateTime endTime, string name, string centerID, string stationID, string doctorAndNurse, string driver, string stretcherBearersI, string alarmReason,
                                        string medicalJudge, string localAddress, string sendAddress, string dispatcher, string time, string area, string result, string banCi, string helpType, string eventDispatchCenterID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch
            sb.Append(EnumSqlAppnd.TZTaskAbendReason());//2020-12-02 zch

            sb.Append(@"select
                            tt.任务编码
                            ,tt.事件编码
                            ,tt.任务流水号
                            ,姓名=(tac.患者姓名)
                            ,患者地址=tac.现场地址
                            ,主诉=tac.主诉
                            ,挂机时刻= case when tac.挂起时刻<>'' then null else convert(varchar(8),结束时刻,114) end
                            ,挂单时刻= tac.挂起时刻
                            ,挂单时长=DATEDIFF(MINUTE,tac.挂起时刻,发送指令时刻)
                            ,电话=tac.联系电话
                            ,受理时刻=tae.首次受理时刻
                            ,派车时刻=convert(varchar(8),首次派车时刻,114)
                            ,发送指令时刻=convert(varchar(8),发送指令时刻,114)
                            ,出车时刻=convert(varchar(8),出车时刻,114)
                            ,到达现场时刻=convert(varchar(8),到达现场时刻,114)
                            ,返回站中时刻=convert(varchar(8),返回站中时刻,114)
                            ,到达医院时刻=convert(varchar(8),到达医院时刻,114)
                            ,收到指令时刻=convert(varchar(8),接收命令时刻,114)
                            ,病家上车时刻=convert(varchar(8),离开现场时刻,114)
                            ,车辆=ta.车牌号码
                            ,反应时间=datediff(MINUTE,tt.接收命令时刻,tt.到达现场时刻)
                            ,现场处理时间=datediff(MINUTE,tt.到达现场时刻,tt.离开现场时刻)
                            ,送往地点=tac.送往地点
                            ,司机=tt.司机
                            ,医生=tt.医生
                            ,护士=tt.护士
                            ,送院时间=DATEDIFF(MINUTE,tt.离开现场时刻,tt.到达医院时刻)
                            ,收费=mpc.PaidMoney
                            ,欠费=(case when mpc.ReceivableTotal>=mpc.PaidMoney then mpc.ReceivableTotal-mpc.PaidMoney else 0 end)
                            ,出车结果=case when tt.是否正常结束=1 then '正常结束'
                            when tt.是否正常结束=0 and tt.异常结束原因编码 in (@已救治,@死亡不送,@病人不去,@车到人走) then '放空车'
                            when tt.是否正常结束=0 and tt.异常结束原因编码 not in (@已救治,@死亡不送,@病人不去,@车到人走,-1) then '中止任务'
                            else '其他'
                            end
                            ,所属分站=ts.名称
                            ,驶向现场时刻=convert(varchar(8),出车时刻,114)
                            ,途中待命时刻 = convert(varchar(8),完成时刻,114)
                            ,班次=case when convert(varchar(10),tt.生成任务时刻,114)>'08:00:00' and convert(varchar(10),tt.生成任务时刻,114)<'20:00:00' then '白班' else '夜班' end
                            ,PatientVersion= mpr.PatientVersion
                            ,DiseasesClassification=mpr.DiseasesClassification
                            ,IllnessClassification=mpr.IllnessClassification
                            ,中心编码=ts.中心编码
                            ,分站编码=tt.分站编码
                            ,判断=tac.病种判断
                            ,担架工=tt.担架工
                            ,区域=tae.区域
                            ,调度员=tp.姓名
                            ,超过1分钟受理电话=case when datediff(second,通话时刻,结束时刻)>60 then tp.姓名 else ' ' end
                            ,电话受理时间=DATEDIFF(SECOND,通话时刻,结束时刻)
                            ,表单受理时间=DATEDIFF(SECOND,开始受理时刻,发送指令时刻)
                            ,呼救类型=tzaet.名称
                            ,迟缓放车调度员=case when tae.事件类型编码 in (@救治,@转院) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >5 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 when tae.事件类型编码=@回家 then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 when tae.事件类型编码 in (@转分中心急,@转长途,@其它,@转分中心非,@特殊事件,@跨省,@保障,@送担架) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN tp.姓名 
                                                      ELSE ' ' END) 
                                                 ELSE ' ' 
                                                 END
                            ,是否迟缓放车=case when tae.事件类型编码 in (@救治,@转院) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >5 THEN 1 
                                                      ELSE 0 END) 
                                                 when tae.事件类型编码=@回家 then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN 1
                                                      ELSE 0 END) 
                                                 when tae.事件类型编码 in (@转分中心急,@转长途,@其它,@转分中心非,@特殊事件,@跨省,@保障,@送担架) then (CASE                       
                                                      WHEN DATEDIFF(minute, 首次受理时刻, 发送指令时刻) >30 THEN 1
                                                      ELSE 0 END) 
                                                 ELSE 0 
                                                 END
                            ,迟缓接听=case when 振铃时刻!='' and (datediff(second,振铃时刻,通话时刻)>10) then tp.姓名 else  ' ' end 
                                into #temp
                                from dbo.TTask tt
                                left join dbo.TAcceptEvent tac on tt.事件编码=tac.事件编码 and tac.受理序号=tt.受理序号
                                left join dbo.TAlarmEvent tae on tt.事件编码=tae.事件编码
                                left join dbo.TAlarmCall tal on tt.事件编码=tal.事件编码 and tal.是否呼出=0
                                --and tal.通话类型编码!=8
                                left join dbo.TAmbulance ta on ta.车辆编码=tt.车辆编码
                                left join dbo.TStation ts on ts.编码=tt.分站编码 ");

            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientCharge mpc on mpc.TaskCode=tt.任务编码 and mpc.PatientOrder=1");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.M_PatientRecord mpr on mpr.TaskCode=tt.任务编码 and mpr.PatientOrder=1");
            sb.Append(@"
                            left join TPerson tp on tp.编码=tae.首次调度员编码 and tp.类型编码=2
                            left join TZAlarmEventType tzaet on tzaet.编码=tae.事件类型编码
                            where tae.首次受理时刻>'" + beginTime + "' and tae.首次受理时刻<'" + endTime + @"' and tae.是否测试=0  ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"                
                            

                            select tt.任务编码,收到指令的按键方式,驶向现场的按键方式,到达现场的按键方式,病人上车的按键方式,到达医院的按键方式,途中待命的按键方式,站内待命的按键方式
                            ,tp.工号
                            into #temp2
                            from TTask tt 
                            left join 
                            (select a.任务编码,驶向现场的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=2 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=2 
                            ) t2 on t2.任务编码=tt.任务编码

                            left join ( select distinct(a.任务编码),到达现场的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=3 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=3 
                            ) t3 on t3.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),病人上车的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=4 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=4 
                            ) t4 on t4.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),到达医院的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=5 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=5 
                            ) t5 on t5.任务编码=tt.任务编码

                            left join (select distinct(a.任务编码),途中待命的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=6 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=6 
                            ) t6 on t6.任务编码=tt.任务编码

                            left join (select a.任务编码,站内待命的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=7 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=7 
                            ) t7 on t7.任务编码=tt.任务编码

                            left join (select a.任务编码,收到指令的按键方式=case when 操作来源编码=1  then '台' when 操作来源编码=2 then '车载' else '' end
                            from TAmbulanceStateTime a
                           ,(select 任务编码,min(时刻值) 时刻值 from TAmbulanceStateTime where 车辆状态编码=1 group by 任务编码) b 
                            where a.任务编码=b.任务编码 and a.时刻值=b.时刻值 and 车辆状态编码=1 
                            ) t8 on t8.任务编码=tt.任务编码

                            left join TPerson tp on tp.编码=tt.责任调度人编码
                            left join TAlarmEvent tae on tae.事件编码=tt.事件编码
                            where 生成任务时刻>'" + beginTime + "' and 生成任务时刻<='" + endTime + @"'  ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"                

                            select
                            t.姓名,任务流水号,患者地址,主诉,超过1分钟受理电话,电话,挂机时刻
                            ,挂单时刻,挂单时长,迟缓放车调度员,是否迟缓放车,迟缓接听
                            ,受理时刻
                            ,发送指令时刻,出车时刻,到达现场时刻
                            ,返回站中时刻,到达医院时刻,途中待命时刻,驶向现场时刻,收到指令时刻,病家上车时刻
                            ,响应时间=case when DATEDIFF(SECOND,收到指令时刻,驶向现场时刻)>0 then DATEDIFF(SECOND,收到指令时刻,驶向现场时刻) else null end
                            ,现场处理时间,车辆
                            ,收到指令的按键方式,驶向现场的按键方式
                            ,到达现场的按键方式,病人上车的按键方式
                            ,到达医院的按键方式,途中待命的按键方式
                            ,站内待命的按键方式,反应时间
                            ,交接时间=case when DATEDIFF(MINUTE,到达医院时刻,途中待命时刻)>0 then DATEDIFF(MINUTE,到达医院时刻,途中待命时刻) else null end
                            ,送往地点,司机,医生,护士,调度员,送院时间
                            ,收费,欠费,班次,出车结果
                            ,所属分站,中心编码,分站编码
                            ,判断
                            ,电话受理时间
                            ,担架工,区域
                            ,工号
                            ,表单受理时间
                            ,呼救类型
                            from #temp t
                            left join #temp2 t2 on t2.任务编码=t.任务编码
                   where 受理时刻>= '" + beginTime + "' and 受理时刻<'" + endTime + @"'  
                            ");
            WhereClauseUtility.AddInSelectQuery("t.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("t.分站编码", stationID, sb);
            WhereClauseUtility.AddStringLike("t.司机", driver, sb);
            WhereClauseUtility.AddStringLike("t.姓名", name, sb);
            WhereClauseUtility.AddStringLike("t.医生", doctorAndNurse, sb);
            WhereClauseUtility.AddStringLike("t.担架工", stretcherBearersI, sb);
            WhereClauseUtility.AddStringLike("t.主诉", alarmReason, sb);
            WhereClauseUtility.AddStringLike("t.判断", medicalJudge, sb);
            WhereClauseUtility.AddStringLike("t.患者地址", localAddress, sb);
            WhereClauseUtility.AddStringLike("t.送往地点", sendAddress, sb);
            WhereClauseUtility.AddStringLike("t.调度员", dispatcher, sb);
            WhereClauseUtility.AddStringEqual("t.区域", area, sb);
            WhereClauseUtility.AddStringEqual("t.出车结果", result, sb);
            WhereClauseUtility.AddStringEqual("t.班次", banCi, sb);
            WhereClauseUtility.AddStringEqual("t.呼救类型", helpType, sb);
            if (time == "")
            { }
            else
            { sb.Append(@" and 电话受理时间>'" + time + @"'"); }
            sb.Append(@" and 是否迟缓放车=1 "); //add 只取迟缓放车任务流水
            sb.Append(@" order by 受理时刻
                         drop table #temp
                         drop table #temp2
                      ");


            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        
        
        /// <summary>
        /// 急救中心任务流水表小结 2016-12-08 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_JJZXRWXJ(DateTime beginTime, DateTime endTime,string name, string centerID, string stationID, string doctorAndNurse, string driver, string stretcher, string alarmReason,
                                        string medicalJudge, string localAddress, string sendAddress, string dispatcher, string time, string area, string result, string banCi, string eventDispatchCenterID)
        {
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch
            sb.Append(EnumSqlAppnd.TZAcceptEventType());//2020-12-02 zch
            sb.Append(EnumSqlAppnd.TZTaskAbendReason());//2020-12-02 zch

            sb.Append(@"select 
                        sum(case when tac.受理类型编码 in (@正常派车,@正常挂起,@增援派车,@增援挂起,@欲派无车,@唤醒派车,@撤销待派,@改派派车,@预约挂起,@落单,@存单) then 1 else 0 end) as 受理数
                        ,派车数=count(tt.任务编码)
                        ,正常完成=SUM(case when tt.是否正常结束=1 then 1 else 0 end)
                        ,中止=SUM(case when tt.异常结束原因编码 not in (@已救治,@死亡不送,@病人不去,@车到人走,-1) then 1 else 0 end)
                        ,空车=sum(case when tt.异常结束原因编码 in(@已救治,@死亡不送,@病人不去,@车到人走) then 1 else 0 end)
                        ,救治=SUM(CASE WHEN 事件类型编码 in (@救治)   THEN 1 ELSE 0 END)
                        from dbo.TAcceptEvent tac
                        left join dbo.TAlarmEvent tae on tac.事件编码 = tae.事件编码 and tae.是否测试 = 0    
                        left join dbo.TAlarmCall ta on ta.事件编码=tac.事件编码 and 是否呼出=0
                        left join TTask tt on tt.事件编码=tac.事件编码 
                        and tt.受理序号=tac.受理序号
                        where tae.首次受理时刻>'" + beginTime + "' and tae.首次受理时刻<'" + endTime + @"'
                        ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 取任务类型（任务流水表）
        //取任务类型 2016-12-09 周志猛
        public object GetTaskType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAlarmEventType
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取伤病程度（任务流水表）
        //取任务类型 2016-12-09 周志猛
        public object GetIllLevel()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZIllState
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取特殊要求（任务流水表）
        //取特殊要求 2016-12-09 周志猛
        public object GetSpecialRequest()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZSpecialRequest
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取地址类别（任务流水表）
        //取地址类别 2016-12-09 周志猛
        public object GetLocalType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZLocalAddrType
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 取人员类型
        //取人员类型 2016-12-18 周志猛
        public object GetPersonType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TRole
                        where 是否有效=1 and 编码 in (3,4,6)");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion


        #region 医疗急救中心患者欠费催收情况登记表
        /// <summary>
        /// 医疗急救中心患者欠费催收情况登记表 2016-12-12 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_QFQKCS(DateTime beginTime, DateTime endTime, string name, string centerID, string stationID, string doctorAndNurse, string driver, string stretcherBearers)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZTaskAbendReason());//2020-12-02 zch

            sb.Append(@"select
                        救护类型=PatientVersion
                        ,现场地址=LocalAddress
                        ,送往地点=SendAddress
                        ,患者姓名=Name
                        ,手机号=ContactTelephone
                        --,备注=Remark
                        ,医生=DoctorAndNurse
                        ,驾驶员=Driver
                        ,担架员=StretcherBearersI
                        ,车牌号=ta.车牌号码
                        ,欠费日期=convert(varchar(10),mpc.Date,120)
                        ,应收金额=mpc.ReceivableTotal
                        ,车费=mpc.CarFee
                        ,医疗费=isnull(mpc.EmergencyFee,0)+isnull(mpc.DrugFeeTotal,0)+isnull(mpc.ExamineFeeTotal,0)+isnull(mpc.ConsumableFeeTotal,0)+isnull(mpc.MeasureFeeTotal,0)
                        ,实收金额=mpc.PaidMoney
                        --,实收人=
                        --,实收发票号
                        --,欠费原因
                        --,欠费情况核实人
                        --,患者/家属确认签字
                        from dbo.M_PatientRecord mpr
                        left join dbo.M_PatientCharge mpc on mpc.TaskCode=mpr.TaskCode and mpr.PatientOrder=mpc.PatientOrder
                        ");

            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TTask tt on tt.任务编码=mpr.TaskCode");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TAmbulance ta on ta.车辆编码=tt.车辆编码");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ts.编码=tt.分站编码");
            sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TAlarmEvent tae on tae.事件编码=tt.事件编码");
            sb.Append(@"
                           where tt.生成任务时刻>'" + beginTime + "' and tt.生成任务时刻<'" + endTime + @"'
                           --and tt.异常结束原因编码 not in (101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,121,123,124,125)
                           and tt.异常结束原因编码 not in (@已救治,@死亡不送,@病人不去,@车到人走,@出车后病家退车,@突发事件,@其他)
                           and PatientVersion not in ('空车','其他') and PaidMoney=0 and tae.是否测试=0 ");
            WhereClauseUtility.AddInSelectQuery("ts.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);
            //WhereClauseUtility.AddStringEqual("mpr.PatientVersion", eventType, sb);
            WhereClauseUtility.AddStringEqual("mpr.Driver", driver, sb);
            WhereClauseUtility.AddStringEqual("mpr.Name", name, sb);
            WhereClauseUtility.AddStringLike("mpr.DoctorAndNurse", doctorAndNurse, sb);
            WhereClauseUtility.AddStringEqual("mpr.StretcherBearersI", stretcherBearers, sb);
            sb.Append(@"order by 欠费日期
                      ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        #region 取送往医院
        //取送往医院 2016-12-22 周志猛
        public object GetHospital(string eventDispatchCenterID)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from THospitalInfo
                        where 是否有效=1");
            //WhereClauseUtility.AddStringEqual("中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion

        #region 医院告知流水表
        /// <summary>
        /// 医院告知流水表 2017-05-17 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_YYGZ(DateTime beginTime, DateTime endTime, string centerID, string stationID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(@"  select
                                tl.任务编码
                                ,任务流水号
                                ,现场地址
                                ,病人姓名=tl.姓名
                                ,tl.性别
                                ,tl.年龄
                                ,主诉
                                ,初步判断
                                --,告知医院时刻
                                ,告知医院=tgzhi.名称
                                ,医生
                                ,驾驶员=tt.司机
                                ,担架工
                                ,调度=tp.姓名
                                into #temp
                                from TLGaoZhiPatient tl
                                left join TTask tt on tt.任务编码=tl.任务编码
                                left join TAcceptEvent tac on tac.事件编码=tt.事件编码 and tac.受理序号=tt.受理序号
                                left join TAlarmEvent tae on tae.事件编码=tt.事件编码
                                left join TGaoZhiHospitalInfo tgzhi on tgzhi.编码=tl.医院编码
                                left join TPerson tp on tp.编码=tac.责任受理人编码
                                left join TCenter tc on tc.编码=tt.中心编码
                                left join TStation ts on ts.编码=tt.分站编码
                                where 生成任务时刻>'" + beginTime+"' and 生成任务时刻<='"+endTime+@"' 
                                and tae.是否测试=0  ");
            WhereClauseUtility.AddInSelectQuery("tt.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);

            sb.Append(@"select 
                                任务编码
                                ,min(时刻值) 时刻值 
                                into #temp1
                                from TAmbulanceStateTime 
                                where 车辆状态编码=1 and 时刻值>'" +beginTime+"' and 时刻值<='"+endTime+@"' 
                                group by 任务编码

                                select 
                                任务编码
                                ,min(时刻值) 时刻值 
                                into #temp2
                                from TAmbulanceStateTime 
                                where 车辆状态编码=2 and 时刻值>'" + beginTime + "' and 时刻值<='" + endTime + @"' 
                                group by 任务编码

                                select 
                                任务编码
                                ,min(时刻值) 时刻值 
                                into #temp3
                                from TAmbulanceStateTime 
                                where 车辆状态编码=3 and 时刻值>'" + beginTime + "' and 时刻值<='" + endTime + @"' 
                                group by 任务编码

                                select 
                                任务编码
                                ,min(时刻值) 时刻值 
                                into #temp4
                                from TAmbulanceStateTime 
                                where 车辆状态编码=4 and 时刻值>'" + beginTime + "' and 时刻值<='" + endTime + @"' 
                                group by 任务编码

                                select 
                                任务流水号=t.任务流水号
                                ,现场地址=t.现场地址
                                ,病人姓名=t.病人姓名
                                ,性别=t.性别
                                ,年龄=t.年龄
                                ,主诉=t.主诉
                                ,初步判断=t.初步判断
                                ,收到指令=t1.时刻值
                                ,驶向现场=t2.时刻值
                                ,到达现场=t3.时刻值
                                ,病人上车=t4.时刻值
                                ,告知医院=t.告知医院
                                ,医生=t.医生
                                ,驾驶员=t.驾驶员
                                ,担架工=t.担架工
                                ,调度=t.调度
                                from #temp t
                                left join #temp1 t1 on t1.任务编码=t.任务编码
                                left join #temp2 t2 on t2.任务编码=t.任务编码
                                left join #temp3 t3 on t3.任务编码=t.任务编码
                                left join #temp4 t4 on t4.任务编码=t.任务编码

                                drop table #temp
                                drop table #temp1
                                drop table #temp2
                                drop table #temp3
                                drop table #temp4  ");

            //WhereClauseUtility.AddInSelectQuery("tt.中心编码", centerID, sb);
            //WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion 

        #region 出车超时流水表
        /// <summary>
        /// 出车超时流水表 2017-05-17 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_CCCS(DateTime beginTime, DateTime endTime, string centerID, string stationID,  string eventDispatchCenterID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(@"  select
                            distinct(tg.任务编码),
                            车牌号=实际标识,
                            送往地点,
                            医生,
                            司机,
                            担架工
                            from TGPS tg
                            left join TTask tt on tt.任务编码=tg.任务编码
                            left join TAcceptEvent tac on tac.事件编码=tt.事件编码 and tac.受理序号=tt.受理序号
                            left join TCenter tc on tc.编码=tt.中心编码
                            left join TStation ts on ts.编码=tt.分站编码
                            where 工作状态编码=2 and 速度=0
                            and 生成任务时刻>'"+beginTime+"' and 生成任务时刻<='"+endTime+@"'  ");
            WhereClauseUtility.AddStringEqual("tt.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            WhereClauseUtility.AddInSelectQuery("tt.中心编码", centerID, sb);
            WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);

            sb.Append(@"order by tg.任务编码 ");

            //WhereClauseUtility.AddInSelectQuery("tt.中心编码", centerID, sb);
            //WhereClauseUtility.AddInSelectQuery("tt.分站编码", stationID, sb);

            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion 


        #region 外伤病人转送医院流水表
        /// <summary>
        /// 外伤病人转送医院流水表 2017-11-08 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_WSBRZSYY(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch

            sb.Append(@"  create table #a
                            (Hospital varchar(50)
                            )
                            INSERT INTO #a VALUES ('松江中心医院')
                            INSERT INTO #a VALUES ('一院松江新院')
                            INSERT INTO #a VALUES ('闵行区中心医院')
                            INSERT INTO #a VALUES ('武警医院')
                            INSERT INTO #a VALUES ('455医院')
                            INSERT INTO #a VALUES ('八五医院')
                            INSERT INTO #a VALUES ('闵行中医医院')
                            INSERT INTO #a VALUES ('九亭医院')
                            select 
                            送往地点,现场地址,
                            判断=tac.病种判断
                            ,医生
                            ,驾驶员=tt.司机
                            ,担架员=tt.担架工
                            into #b
                            from TAcceptEvent tac
                            inner join TAlarmEvent tae on tae.事件编码=tac.事件编码
                            inner join TTask tt on tac.事件编码=tt.事件编码 and tac.受理序号=tt.受理序号
                            where 生成任务时刻>'" + beginTime + "' and 生成任务时刻<='" + endTime + @"'  and 
                            是否测试=0 and 送往地点 is not null and 送往地点<>''  
                            and tae.事件类型编码=@救治 and tac.病种判断 like '%外伤%' ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"  
                            group by 送往地点,现场地址,tac.病种判断,医生,tt.司机,tt.担架工


                            select Hospital,现场地址,判断,医生,
                            驾驶员,担架员,送往地点
                            from #a a
                            inner join #b b on b.送往地点 like '%'+a.Hospital+'%'
                            group by Hospital,送往地点,现场地址,判断,医生,驾驶员,担架员
                            drop table #a
                            drop table #b  ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion 

        #region 中心医院外伤病人转院流水表
        /// <summary>
        /// 中心医院外伤病人转院流水表 2017-11-08 周志猛
        /// </summary>
        /// <param name="BeginTime"></param>
        /// <param name="EndTime"></param>
        /// <returns></returns>
        public DataTable Get_LS_ZXYYWSBRZY(DateTime beginTime, DateTime endTime, string eventDispatchCenterID)
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.MainConnectionString);
            string eventCodeB = beginTime.ToString("yyyyMMdd") + "00000000";
            string eventCodeE = endTime.AddDays(1).ToString("yyyyMMdd") + "00000000";
            string taskCodeB = eventCodeB + "0000";
            string taskCodeE = eventCodeE + "0000";
            StringBuilder sb = new StringBuilder();
            sb.Append(EnumSqlAppnd.TZAlarmEventType()); //2020-12-02 zch

            sb.Append(@"  create table #a
                            (Hospital varchar(50)
                            )
                            INSERT INTO #a VALUES ('一院松江新院')
                            INSERT INTO #a VALUES ('上海市第六人民医院')

                            select 
                            送往地点,现场地址,
                            判断=tac.病种判断
                            ,医生
                            ,驾驶员=tt.司机
                            ,担架员=tt.担架工
                            into #b
                            from TAcceptEvent tac
                            inner join TAlarmEvent tae on tae.事件编码=tac.事件编码
                            inner join TTask tt on tac.事件编码=tt.事件编码 and tac.受理序号=tt.受理序号
                            where 生成任务时刻>'" + beginTime + "' and 生成任务时刻<='" + endTime + @"'  and 
                            是否测试=0 and 送往地点 is not null and 送往地点<>''  
                            and tae.事件类型编码=@转院 and tac.病种判断 like '%外伤%'
                            and 现场地址 like '%中心医院%'  ");
            WhereClauseUtility.AddStringEqual("tae.中心编码", eventDispatchCenterID, sb); //2020-11-22 zch
            sb.Append(@"  
                            group by 送往地点,现场地址,tac.病种判断,医生,tt.司机,tt.担架工


                            select Hospital,现场地址,判断,医生,
                            驾驶员,担架员,送往地点
                            from #a a
                            inner join #b b on b.送往地点 like '%'+a.Hospital+'%'
                            group by Hospital,送往地点,现场地址,判断,医生,驾驶员,担架员
                            drop table #a
                            drop table #b  ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion 

        #region 取呼救类型
        public object GetHelpType()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"
                        select 编码,名称 from TZAlarmEventType
                        where 是否有效=1 ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.AttemperConnectionString, CommandType.Text, sb.ToString(), null);
            List<CheckModelExt> list = new List<CheckModelExt>();
            if (ds.Tables[0].Rows.Count > 0)
            {
                CheckModelExt info = new CheckModelExt();
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    info = new CheckModelExt();
                    info.ID = dr["编码"].ToString();
                    info.Name = dr["名称"].ToString();

                    list.Add(info);
                }
            }
            return list;

        }
        #endregion


        #region 入库单子表流水， 采用入库页面嵌套打印内容 ，参数为 entryCode 即可，通过主表ID 获取子表内容  2018-12-11 zch

        public DataTable Get_LS_XEntryDetailByCode(string entryListCode)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select  供应商=m.Vendor
                                ,生产厂家=m.Manufacturer
                                ,物品编码=MCode
                                ,物品名称=m.Name
                                ,规格=m.Specification
                                ,单位=td.Name
                                ,入库数量=en.EntryCounts
                                ,单价=m.UnitPrice
                                ,金额小计=en.TotalPrice
                                ,备注=en.Remark
                                ,入库单号=en.EntryDetailCode
                                ,入库方向=st.Name
                                ,入库时间=CONVERT(varchar(100), en.EntryDate, 20)
                                ,有效期=CONVERT(varchar(100), en.ValidityDate, 20)
                                ,入库批号=en.RealBatchNo
                                from I_EntryDetail en
								left join I_Entry e on e.EntryCode=en.EntryCode
                                left join I_Material m on m.ID=en.MaterialID
                                left join TDictionary td on td.ID=m.Unit
                                left join I_Storage st on st.StorageID=e.EntryStorageID
                                left join P_User us on us.ID=en.OperatorCode
                        ");
            sb.Append(" where 1=1 ");
            WhereClauseUtility.AddStringEqual("en.EntryCode", entryListCode, sb);
            sb.Append(" order by en.EntryDate desc ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }

        #endregion

        #region 固定资产报废申请单 2019-11-07 孙润
        public DataTable GetAssetsList(string BianMa)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"select 固定资产编码,资产名称,型号,购建日期,name.仓库名称 from FIXED_Matetial main
                       left join FIXED_Storage name on name.仓库编码=main.当前仓库编码 where 编码='" + BianMa + "' ");
            //SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(SqlHelper.AttemperConnectionString);
            //sb.Append(" left join ").Append(builder.InitialCatalog).Append(".dbo.TStation ts on ts.编码=crm.分站 ");
            //sb.Append(" where crm.编码='" + BianMa + "' ");
            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
            return ds.Tables[0];
        }
        #endregion

        //出库单流水 查询条件与出库单查询条件一致
   
//              public object GetDeliveryList( DateTime startTime, DateTime endTime, string DeliveryCode, string DeliveryType, string SelectStorage, string  TargetStorage, List<string> listMaterialType, string MaterialID, string IFCheck)
//        {
               
//            var q = (from dd in db.I_DeliveryDetail
//                     select new
//                     {
//                         //物资信息
//                         MaterialMTypeID = dd.I_Material.MTypeID, //物资分类编码
//                         MaterialName = dd.I_Material.Name, //物资名称
//                         MaterialManufacturer = dd.I_Material.Manufacturer, //制造商
//                         MaterialVendor = dd.I_Material.Vendor, //供应商
//                         MaterialAlarmCounts = dd.I_Material.AlarmCounts, //报警数量
//                         MaterialSpecification = dd.I_Material.Specification, //规格
//                         MaterialRealPrice = dd.I_Material.RealPrice, //销售价格
//                         MaterialUnit = dd.I_Material.Unit, //单位
//                         MaterialUnitName = dd.I_Material.TDictionary2.Name, //单位名称
//                         EntryStorageName = dd.I_Storage.Name,     //翻译仓库名称
//                         TargetStorageName = dd.I_Storage1.Name,   //目标仓库名称
//                         OperatorName = dd.P_User.Name,            //操作人员名称
//                         MCode = dd.I_Material.MCode,  //物资代码

//                         //物资出库主表信息
//                         ConsigneeID = dd.I_Delivery.ConsigneeID, // 收货人编码
//                         Remark = dd.I_Delivery.Remark,  //出货单备注
//                         DeliveryType = dd.I_Delivery.DeliveryType, //出库类型编码
//                         DeliveryTypeName = dd.I_Delivery.TDictionary.Name,  //出库单类型名称

//                         //出库详细信息
//                         DeliveryDetailCode = dd.DeliveryDetailCode, //物资出库编码
//                         DeliveryCode = dd.DeliveryCode,    //出库单编码
//                         RealBatchNo = dd.RealBatchNo, //实际批次号
//                         BatchNo = dd.BatchNo,  //系统批次号
//                         DeliveryCounts = dd.DeliveryCounts,   //出库数量
//                         DeliveryTime = dd.DeliveryTime,  //出库时间
//                         OperatorCode = dd.OperatorCode,  //操作人员编码
//                         EntryStorageCode = dd.EntryStorageCode,     //来源仓库编码
//                         TargetStorageCode = dd.TargetStorageCode,   //目标仓库编码
//                         TargetEntryDetailCode = dd.TargetEntryDetailCode,  //来源入库编码
//                         DetailRemark = dd.Remark,                          //备注
//                         RedDeliveryDetailCode = dd.RedDeliveryDetailCode,  // 红冲编码
//                         MaterialID = dd.MaterialID,   // 物资编码
//                         IFCheck = dd.IFCheck,
//                         CheckTime = dd.CheckTime,
//                         ReportMonth = dd.ReportMonth
//                     });

         

//            if (!string.IsNullOrEmpty(DeliveryCode))  //出库编码
//            {
//                q = q.Where(d => d.DeliveryCode == DeliveryCode);
//            }
//            if (!string.IsNullOrEmpty(DeliveryType)) //出库类型
//            {
//                q = q.Where(d => d.DeliveryType == DeliveryType);
//            }

//            if (!string.IsNullOrEmpty(MaterialID)) //物资ID
//            {
//                int id = int.Parse(MaterialID);
//                q = q.Where(d => d.MaterialID == id);
//            }
//            if (listSourceStorageID != null)
//            {
//                q = q.Where(d => listSourceStorageID.Contains(d.EntryStorageCode));
//            }
//            if (listTargetStorageID != null)
//            {
//                q = q.Where(d => listTargetStorageID.Contains(d.TargetStorageCode));
//            }
//            if (listMaterialType != null)
//            {
//                q = q.Where(d => listMaterialType.Contains(d.MaterialMTypeID));
//            }

//            if (!string.IsNullOrEmpty(IFCheck)) //是否审核， 2016-4-11 新增
//            {

//                bool tempIFCheck = Convert.ToBoolean(IFCheck);
//                q = q.Where(d => d.IFCheck == tempIFCheck);
//            }

//            StringBuilder sb = new StringBuilder();
//            sb.Append(@"select  物品编码=MCode
//                                ,物品名称=ma.Name
//                                ,规格=ma.Specification
//                                ,单位=td2.Name
//                                ,出库数量=dd.DeliveryCounts
//                                ,单价=ma.UnitPrice
//                                ,备注=dd.Remark
//                                --,入库数量=en.EntryCounts
//								--,入库总金额=en.TotalPrice
//								,出库单号=dd.DeliveryCode
//								,出库方向=st2.Name
//								,出库日期=CONVERT(varchar(100), dd.DeliveryTime, 20)
//                                ,有效期=CONVERT(varchar(100), isu.ValidityDate, 20)
//                                ,出库批号=dd.RealBatchNo,生产厂家=ma.Manufacturer
//                        from I_DeliveryDetail dd
//                        left join I_Material ma on ma.ID=dd.MaterialID
//                        --left join I_EntryDetail en on en.EntryDetailCode=dd.DeliveryDetailCode
//                        left join I_Delivery dl on dl.DeliveryCode=dd.DeliveryCode
//                        left join I_Storage st1 on st1.StorageID=dd.EntryStorageCode
//                        left join I_Storage st2 on st2.StorageID=dd.TargetStorageCode
//                        left join P_User us1 on us1.ID=dd.OperatorCode
//						left join P_User us2 on us2.ID=dl.ConsigneeID
//                        left join TDictionary td1 on td1.ID=dl.DeliveryType
//                        left join TDictionary td2 on td2.ID=ma.Unit ");
					   
                        
//            sb.Append(" where 1=1 ");

//            WhereClauseUtility.AddDateTimeGreaterThan("dd.DeliveryTime", startTime, sb);
//            WhereClauseUtility.AddDateTimeLessThan("dd.DeliveryTime", endTime, sb);

//            WhereClauseUtility.AddStringEqual("dd.DeliveryCode", DeliveryCode, sb);
//            WhereClauseUtility.AddStringEqual("dl.DeliveryType", DeliveryType, sb);
//            WhereClauseUtility.AddStringEqual("dd.MaterialID", MaterialID, sb);

//           // WhereClauseUtility.AddInSelectQuery("dd.EntryStorageCode", listSourceStorageID, sb);
//            if (listSourceStorageID!= null)
//                listSourceStorageID.Contains()


//            WhereClauseUtility.AddStringInSelectQuery("ma.MTypeID", classification, sb);
         
//            WhereClauseUtility.AddStringLike("dd.DeliveryCode", deliveryListCode, sb);
       
//            WhereClauseUtility.AddStringEqual("us2.Name", receiver, sb);
//            WhereClauseUtility.AddStringEqual("dl.AmbulanceCode", receiverAmbulance, sb);
//            WhereClauseUtility.AddStringLike("us1.Name", operater, sb);//新增经办人查询条件 2016-07-01 youhao
//            sb.Append(" order by dd.DeliveryTime desc ");
//            DataSet ds = SqlHelper.ExecuteDataSet(SqlHelper.MainConnectionString, CommandType.Text, sb.ToString(), null);
//            return ds.Tables[0];
//        }

    }
}